题目:
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.
思路:
这是动态规划里面最简单的一种形式:由于每一步只能走1步或者2步,所以递推公式为:dp[n] = dp[n-1] + dp[n-2]。是不是非常熟悉?没错,就是著名的斐波那契序列!注意到dp[n]只和与它最临近的2个元素有关,所以空间复杂度可以优化到O(n)。时间复杂度已经是最优的O(n)了。
代码:
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
int prev = 1, curr = 2;
for (int i = 3; i <= n; ++i) {
curr = prev + curr;
prev = curr - prev;
}
return curr;
}
};