Description
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?
Note: Given n will be a positive integer.
Solution
关键就是无论什么跳法,最后一步要么是1,要么是2。
即从n-1层跳1 step,或者从n-2层跳2 step。
f(n)=f(n-1)+f(n-2)
递归的写法很简单,就是提交的时候总是Time Limit Exceeded,如下。
class Solution {
public:
int climbStairs(int n) {
//f(n)=f(n-1)+f(n-2)
if(n==1)return 1;
if(n==2)return 2;
return climbStairs(n-1)+climbStairs(n-2);
}
};
再写一个非递归的算法。
class Solution {
public:
int climbStairs(int n) {
if(n==1)return 1;
if(n==2)return 2;
int s1=2;//记录前s-1路线总数
int s2=1;//记录前s-2路线总数
int result;
for(int i=3;i<=n;i++)
{
result=s1+s2;
s2=s1;
s1=result;
}
return result;
}
};