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?
递归模式很容易想到,但是超时啦。
class Solution {
public:
int climbStairs(int n) {
if(n<=2){
return n;
}else{
return climbStairs(n-1)+climbStairs(n-2);
}
}
};
所以采用非递归方式
class Solution {
public:
int climbStairs(int n) {
if(n<=2){
return n;
}else{
int pre1 = 1;
int pre2 = 2;
for(int i=3;i<=n;i++){
int temp = pre1 + pre2;
pre1 = pre2;
pre2 = temp;
}
return pre2;
}
}
};