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?
爬楼梯问题,每一次可以爬1阶或者2阶,问爬上N阶的选择法,爬上1阶的选择1种,爬上2阶的选择有2种,
爬上N阶的选择有f(N) = f(N-1)+f(N-2).....
当使用递归算法的时候会超时!!!!!!
class Solution {
public:
int climbStairs(int n) {
if(n==1)
return 1;
if(n==2)
return 2;
return climbStairs(n-1)+climbStairs(n-2);
}
};
Submission Result: Time Limit Exceeded
改进方法后.......
class Solution {
public:
int climbStairs(int n) {
int result,s1=1,s2=2;
if(n==1)
return s1;
if(n==2)
return s2;
for(int i=3;i<=n;i++)
{
result = s1 + s2;
s1 = s2;
s2 = result;
}
return result;
}
};
Submission Result: Accepted