题目描述
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?
class Solution {
public:
int climbStairs(int n) {
if (n <= 1) return 1;
vector<int> dp(n);
dp[0] = 1; dp[1] = 2;
for (int i = 2; i < n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp.back();
}
};
我们可以对空间进行进一步优化,我们只用两个整型变量a和b来存储过程值,首先将a+b的值赋给b,然后a赋值为原来的b,所以应该赋值为b-a即可。这样就模拟了上面累加的过程,而不用存储所有的值,参见代码如下:
class Solution {
public:
int climbStairs(int n) {
int a = 1, b = 1;
while (n--) {
b += a;
a = b - a;
}
return a;
}
};
参考: https://www.cnblogs.com/grandyang/p/4079165.html
这道题和剑指offer上的跳台阶是一样的。