问题:https://leetcode.com/problems/climbing-stairs/?tab=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? 你在爬楼梯。需要n步到达顶端。
每次可以爬上1或2级。有多少种不同的方式到达顶端?
分析:因为可以一次爬1级或者2级。所以F(n)=F(n-1)+F(n-2)。也就是F(n-1)爬1级,F(n-2)爬2级。
C++代码:
class Solution {
public:
int climbStairs(int n) {
int s[n+1];
s[0]=1;
s[1]=1;
for(int i=2;i<n+1;i++){
s[i]=s[i-1]+s[i-2];
}
return s[n];
}
};