文章目录
青蛙跳台阶
要求:
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
思路:
如何跳上第n阶?
方法一:在第n-1阶向上跳1级
方法二:在第n-2阶向上跳2级
所以跳上第n阶的跳法等于 跳上第n-1阶的跳法 加上 跳上第n-2阶的跳法
代码:
//迭代版
public int JumpFloor(int target) {
if (target==1||target==2) return target;
int pre1 = 1;
int pre2 = 2;
int total = pre1+pre2;
for(int i = 3;i<=target;i++){
total = pre1+pre2;
pre1 = pre2;
pre2 = total;
}
return total;
}
//递归版(时间复杂度2的阶乘太高)
public int JumpFloor(int target) {
if(target==1||target==2) return target;
return JumpFloor(target-1)+JumpFloor(target-2);