斐波那契数列
class Solution {
public:
int fib(int n) {
if(n<=1) return n;
vector<int> dp(n+1);
dp[0] = 0;
dp[1] = 1;
for(int i=2;i<=n;i++){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
};
爬楼梯
class Solution {
public:
int climbStairs(int n) {
if(n<=1) return n;
int dp[3];
dp[1] = 1;
dp[2] = 2;
for(int i=3;i<=n;i++){
int sum =dp[1]+dp[2];
dp[1] = dp[2];
dp[2] = sum;
}
return dp[2];
}
};
拓展到m个楼梯
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n + 1, 0);
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i - j >= 0) dp[i] += dp[i - j];
}
}
return dp[n];
}
};
使用最小花费爬楼梯
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int> dp(cost.size());
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < cost.size(); i++) {
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
}
return min(dp[cost.size() - 1], dp[cost.size() - 2]);
}
};