dp套路
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
cpp
复制代码
class Solution {
public:
int fib(int n) {
if (n <= 1) return n;
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];
}
};
cpp
复制代码
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) return n;
int dp[n + 1];
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++){
dp[i] = dp[i - 2] + dp[i - 1];
}
return dp[n];
}
};
cpp
复制代码
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int dp[cost.size() + 1];
dp[0] = dp[1] = 0;
for (int i = 2; i <= cost.size(); i++){
dp[i] = min(cost[i - 1] + dp[i - 1], cost[i - 2] + dp[i - 2]);
}
return dp[cost.size()];
}
};