Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
dp[i]
表示爬到 i
阶的方法数,爬到 i
阶之前必然先爬到 i - 1
或 i - 2
阶,因此爬到 i
阶的方法数就是爬到 i - 1
阶和 i - 2
阶的方法数之和class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
vector<int> dp(n + 1);
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};