题目
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
解答方法一:可用递归思想, 但太慢了,时间复杂度:O(2^lgn),当n逐渐变大时,时间呈指数增长
int climbStairsRecur(int n){
if(n==1) return 1;
if(n==2) return 2;
return climbStairsRecur(n-1)+climbStairsRecur(n-2);
}
方法二:使用动态规划法填表,时间复杂度:O(n)
public class Solution {
public static int climbStairs(int n) {
int[] data=new int[n+1];
data[0]=0;
data[1]=1;
if(n>=2){
data[2]=2;
}
for(int i=3;i<=n;i++){
data[i]=data[i-1]+data[i-2];
}
return data[n];
}
}
直接用变量存储
int climbStairs(int n){
if(n<4)
return n;
int a=2,b=3,c=5;
for(int i=5;i<=n;i++){
a=c; //此处a只是作为变量
c=b+c;
b=a;
}
return c;
}
---EOF---