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.
题意:
N 阶台阶,每次可以爬上一层或者两层,问共多少种爬法。
解答:
1:递归,但是会超市;
2:保存已经计算出的结果,防止超时。
代码:
class Solution {
public:
int climbStairs(int n) {
if(n==1 || n==2) return n;
vector<int> res;
res.push_back(1);
res.push_back(2);
for(int i=2; i<n; i++){
res.push_back(res[i-1]+res[i-2]);
}
return res[n-1];
}
};