题目:
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?
分析:
爬楼梯问题,一开始用了递归,于是TLE了。。于是用了一个数组来记录之前走的方法数。当前楼梯数n的走法可以由n-1和n-2时的走法一起得到。
代码:
class Solution {
public:
int climbStairs(int n) {
int* stairs=new int[n+1];
stairs[1]=1;
stairs[2]=2;
for(int i=3;i<=n;++i){
stairs[i]=stairs[i-1]+stairs[i-2];
}
return stairs[n];
}
};