爬楼梯,每次只能爬一阶或者二阶。问一共有多少中爬法?
// the method of recursive
public class Solution{
public int jumpFloor(int target){
if(target <= 1) return 1;
return jumpFloor(target -1) + jumpFloor(target - 2);
}
}
//the method of iteration
public class Solution{
public int jumpFloor(int target){
if(target <=2 ) return target;
int one = 1;
int two = 0;
int sum = 0;
for(int i=1;i<=target;i++){
sum = one + two;
two = one;
one = sum;
}
return sum;
}
}
跳楼梯,每此可以跳1,2,3...n阶台阶,问一共有多少中跳法?
-
分析
-
n阶台阶可以有的跳法设为f(n)种,若第一次跳了一阶则剩下n-1个台阶,n-1阶跳法为f(n-1)
-
所以可以得出:f(n) = f(n-1) + f(n-2) + f(n-3) + ... + f(n-n)
即:f(n) = f(0) + f(1) +f(2) + ... + f(n-1)
那么:f(n-1) = f(0) + f(1) + f(2) + ... + f(n-2)
f(n) - f(n-1)可以得出f(n) = 2*f(n-1)
-
已知f(1) = 1,f(2) = 2,f(0) = 0;
-
-
代码实现
public class Solution{ public int climbStair(int n){ if(n <= 0) return 0; else if(n == 1) return 1; else return 2*climbStair(n-1); } }