动态规划理论基础
文章链接:https://programmercarl.com/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E7%90%86%E8%AE%BA%E5%9F…
动态规划,简称DP,如果某一问题有很多重叠子问题,使用动态规划是最有效的。所以动态规划中每一个状态一定是由上一个状态推导出来的,这一点就区分于贪心,贪心没有状态推导,而是从局部直接选最优的。比如背包问题:有N件物品和一个最多能背重量为W 的背包。第i件物品的重量是weight[i]
,得到的价值是value[i]
。每件物品只能用一次,求解将哪些物品装入背包里物品价值总和最大。
- 动态规划中
dp[j]
是由dp[j-weight[i]]
推导出来的,然后取max(dp[j], dp[j - weight[i]] + value[i])
。 - 但如果是贪心呢,每次拿物品选一个最大的或者最小的就完事了,和上一个状态没有关系。
动规五部曲:
- 确定dp数组以及下标的含义
- 确定递推公式
- dp数组如何初始化
- 确定遍历顺序
- 打印dp数组,用于debug
动规的常见问题类型:
- 动规基础
- 背包问题
- 打家劫舍
- 股票问题
- 子序列问题
509. 斐波那契数
题目链接:https://leetcode.cn/problems/fibonacci-number/
文档讲解:https://programmercarl.com/0509.%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0.html
视频讲解:https://www.bilibili.com/video/BV1f5411K7mo
思路
- 确定dp数组以及下标的含义:为第i个斐波那契数的值为
dp[i]
- 确定递推公式:
dp[i] = dp[i - 1] + dp[i - 2]
- dp数组如何初始化 :
dp[0] = 1
,dp[1] = 1
- 确定遍历顺序:从前往后遍历
- 打印dp数组,用于debug
代码
class Solution {
public int fib(int n) {
if (n < 2) return n;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i < n + 1; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
分析:时间复杂度:O(n),空间复杂度:O(n)。
70. 爬楼梯
题目链接:https://leetcode.cn/problems/climbing-stairs/
文档讲解:https://programmercarl.com/0070.%E7%88%AC%E6%A5%BC%E6%A2%AF.html
视频讲解:https://www.bilibili.com/video/BV17h411h7UH
思路
- 确定dp数组以及下标的含义:爬i个台阶有
dp[i]
种方法 - 确定递推公式:第i阶的方法数是由i - 1阶和i - 2阶得到的,可以从i - 1阶走一步上来,也可以从i - 2阶走两步上来,所以
dp[i] = dp[i - 1] + dp[i - 2]
- dp数组如何初始化 :
dp[1] = 1
,dp[2] = 2
- 确定遍历顺序:从前往后遍历
- 打印dp数组,用于debug
代码
class Solution {
public int climbStairs(int n) {
if (n <= 2) return n;
int[] dp = new int[n + 1]; // 爬n阶楼梯有dp[i]种方法
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i < dp.length; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
分析:时间复杂度:O(n),空间复杂度:O(n)。
746. 使用最小花费爬楼梯
题目链接:https://leetcode.cn/problems/min-cost-climbing-stairs/
文档讲解:https://programmercarl.com/0746.%E4%BD%BF%E7%94%A8%E6%9C%80%E5%B0%8F%E8%8A%B1%E8%B4%B9%E7…
视频讲解:https://www.bilibili.com/video/BV16G411c7yZ/
思路
- 确定dp数组以及下标的含义:到达i位置的花费为
dp[i]
- 确定递推公式:
dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
- dp数组如何初始化 :
- 确定遍历顺序:
- 打印dp数组,用于debug
代码
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length + 1];
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i <= cost.length; i++) {
dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[cost.length]; // 这里返回的应该是cost数组最大梯子的下一阶
}
}
分析:时间复杂度:O(n),空间复杂度:O(n)。