动态规划理论基础
动态规划问题,我将拆解为如下五步曲,这五步都搞清楚了,才能说把动态规划真的掌握了!
- 确定dp数组(dp table)以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 举例推导dp数组
LeetCode509.斐波那契数
题目链接:509. 斐波那契数 - 力扣(LeetCode)
思路:
正常思路:
class Solution {
public:
int fib(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
if(n > 1) return fib(n - 1) + fib(n -2);
return fib(n);
}
};
dp思路:
class Solution {
public:
int fib(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
vector<int> dp(n + 1);//1.dp下标和含义:第i个数的斐波那契数值是dp[i]
dp[0] = 0,dp[1] = 1;//3.初始化
for(int i = 2; i <= n; i++) {//4.遍历顺序
dp[i] = dp[i - 1] + dp[i - 2];//2.确定的递推公式,状态转移方程
}
return dp[n];//5.推导
}
};
LeetCode70.爬楼梯
思路:
class Solution {
public:
int climbStairs(int n) {
if(n <= 2) return n;
vector<int> dp(n + 1);//dp[i]表示有多少种方法
dp[0] = 0,dp[1] = 1,dp[2] = 2;
for(int i = 3;i <= n; i++) {//遍历
dp[i] = dp[i - 1] + dp[i - 2];//递推公式
}
return dp[n];
}
};
LeetCode746.使用最小花费爬楼梯
题目链接:746. 使用最小花费爬楼梯 - 力扣(LeetCode)
思路:
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
if(cost.size() == 0) return 0;
vector<int> dp(cost.size() + 1);//dp为爬上顶层需要支付的最少费用
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()];
}
};