动态规划,简称DP,主要用来
DP五步:
DP处理的问题:
?
图片来源:代码随想录?
五步曲:
class Solution {
public:
int fib(int n) {
if (n <= 1) return n;
int dp[2];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
int sum = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = sum;
}
return dp[1];
}
};
五步曲:
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) 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];
}
};
五步曲:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int dp0 = 0;
int dp1 = 0;
for (int i = 2; i <= cost.size(); i++) {
int dpi = min(dp0 + cost[i - 2], dp1 + cost[i - 1]);
dp0 = dp1;
dp1 = dpi;
}
return dp1;
}
};