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.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
解法:
这个也是斐波那契数列的一个变种,好多题目都喜欢考这个,本质上是一样的。考虑到最后一步可以跨一步或者两步,那么s(n) = s(n-1) + s(n-1)
class Solution {
public:
int climbStairs(int n) {
if(n == 1) {
return 1;
}
if(n == 2) {
return 2;
}
int curResult = 2;
int lastResult = 1;
for(int i=3; i<=n; i++) {
int temp = curResult;
curResult = curResult + lastResult;
lastResult = temp;
}
return curResult;
}
};
依然需要注意一下边界,最好可以在脑海里面代入具体的值演算一遍。不要犯低级错误。