您的位置:首页 > 其它

青蛙跳阶1小练习

2016-02-28 11:57 274 查看
package cn.itcast.offer1;

/*

* 一只青蛙一次可以跳上1层台阶,也可以跳2层,求该青蛙跳上一个N层的台阶共有多少种跳法

*/

思路分析:

假设青蛙最后一次跳台阶,如果跳1层,则前n-1层有f(n-1)种方法;如果跳2层,则前n-2层有f(n-2)种方法,因此n层台阶共有f(n-1)+f(n-2)=f(n)种跳法;

public class OfferQingwa {

public static void main(String[] args) {

// TODO Auto-generated method stub

int x=method(3);

System.out.println("total="+x);

}

public static int method(int n){

if (n<0){

return -1;

}

else if (n==1){

return 1;

}

else if (n==2){

return 2;

}

else{

return method(n-1)+method(n-2);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: