day38
代码随想录
2024.1.6
开始动态规划!
递归五部曲:
1. 50斐波那契数列
经典的动态规划入门第一题,直接递归五部曲,
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];
}
};
2. 70爬楼梯
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];
}
};
3. 746使用最小代价爬楼梯
这道题初始化开始没有弄清楚
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int> dp(cost.size() + 1);
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i <= cost.size(); i++) {
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[cost.size()];
}
};