题目:
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;
}
};
本文探讨了一个经典的动态规划问题——爬楼梯。通过分析递推关系,我们发现该问题实质上等价于求解斐波那契数列的第n项。文章给出了一个高效的时间复杂度为O(n),空间复杂度为O(1)的解决方案。
365

被折叠的 条评论
为什么被折叠?



