1. LeetCode 322. 零钱兑换
题目链接:https://leetcode.cn/problems/coin-change/description/
文章链接:https://programmercarl.com/0322.零钱兑换.html
视频链接:https://www.bilibili.com/video/BV14K411R7yv/
思路:
硬币无限,即:完全背包
求最少硬币个数,不是组合和排列
物品:coins
背包:总金额为amount的背包
重量:金额
价值:硬币个数
解法
class Solution {
public int coinChange(int[] coins, int amount) {
// 硬币无限 完全背包
// 求最少硬币个数。不是组合和排列
// 物品:coins
// 背包:总金额为amount的背包
// 重量:金额
// 价值:硬币个数
// 1. 定义dp数组
// dp[j]表示总金额j所需的最少硬币个数
int[] dp = new int[amount+1];
// 2.递推公式
// dp[j] = Math.min(dp[j-coins[i]]+1,dp[j]);
// 3.初始化
dp[0] = 0;
for (int i=1;i< dp.length;i++) {
dp[i] = Integer.MAX_VALUE;
}
// 4.遍历顺序 先物品再背包
for (int i=0;i<coins.length;i++) {
for (int j=coins[i];j<=amount;j++) {
//只有dp[j-coins[i]]不是初始最大值时,该位才有选择的必要
if (dp[j - coins[i]] != Integer.MAX_VALUE) {
//选择硬币数目最小的情况
dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
}
}
}
return dp[amount]==Integer.MAX_VALUE?-1:dp[amount];
}
}
注意:使用递推公式之前,必须确保dp[j - coins[i]] != Integer.MAX_VALUE,否则就是在最大值的基础上加一。
2. LeetCode 279.完全平方数
题目链接:https://leetcode.cn/problems/perfect-squares/description/
文章链接:https://programmercarl.com/0279.完全平方数.html
视频链接:https://www.bilibili.com/video/BV12P411T7Br/
思路:
可重复取完全平方数,即完全背包
最少数量,不是组合、排列
物品:[11,22,…,n*n]
背包:和为n的背包
重量:完全平方数
价值:完全平方数的数量
解法:
class Solution {
public int numSquares(int n) {
//可重复取完全平方数 完全背包
//最少数量,不是组合、排列
//物品:[1,2^2,...,n^2]
//背包:和为n的背包
//重量:完全平方数
//价值:完全平方数的数量
int[] nums = new int[n];
for (int i=0;i<n;i++) {
nums[i] = (i+1)*(i+1);
}
//1.定义dp数组
//dp[j]表示和为j的完全平方数最少数量
int[] dp = new int[n+1];
//2.递推公式
//dp[j] = Math.min(dp[j],dp[j-nums[i]]+1);
//3.初始化
int max = Integer.MAX_VALUE;
for (int i=0;i<dp.length;i++) {
dp[i] = max;
}
dp[0]=0;
//4.遍历顺序 先物品再背包
for (int i=0;i<nums.length;i++) {
for (int j=nums[i];j<=n;j++) {
if (dp[j-nums[i]]!=max) {
dp[j] = Math.min(dp[j],dp[j-nums[i]]+1);
}
}
}
return dp[n];
}
}
3. LeetCode 139.单词拆分
题目链接:https://leetcode.cn/problems/word-break/description/
文章链接:https://programmercarl.com/0139.单词拆分.html
视频链接:https://www.bilibili.com/video/BV1pd4y147Rh/
思路:
可重复取,即完全背包
物品有顺序,排列
物品:wordDict
背包: 字符串s的背包
重量:字符串
价值:是否能拼成s
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// 可重复取,即完全背包
// 排列
// 物品:wordDict
// 背包: 字符串s的背包
// 重量:字符串
// 价值:是否能拼成s
//1.定义dp数组 dp[j]表示前j个字符组成的字符串是否有单词拼接成功
boolean[] dp = new boolean[s.length()+1];
//2.递推公式
//if(dp[j-wordDict.get(i).length()]&&(wordDict.get(i).equals(s.substring(j-wordDict.get(i).length(),j)))) dp[j]=true;
//3.初始化
dp[0]=true;
//4.遍历顺序
for (int j=1;j<=s.length();j++) {
for (int i=0;i<wordDict.size();i++) {
int len = wordDict.get(i).length();
if((j-len>=0)&&(wordDict.get(i).equals(s.substring(j-len,j)))&&dp[j-len]) {
dp[j]=true;
break;
}
}
}
return dp[s.length()];
}
}