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?
这道题其实考的就是青蛙跳台阶的问题,本质是斐波那契数列。f(n+2) = f(n) + f(n+1).
- C++ AC代码如下:
class Solution {
public:
int climbStairs(int n) {
if(n == 1 || n == 2)
return n;
int f0 = 1, f1 = 1;
int steps = 0;
for(int i=2; i<=n; i++)
{
steps = f0 + f1;
f0 = f1;
f1 = steps;
}
return steps;
}
};