LeetCode 322. 零钱兑换
题目链接:https://leetcode.cn/problems/coin-change-ii/description/
文章链接:https://programmercarl.com/0322.%E9%9B%B6%E9%92%B1%E5%85%91%E6%8D%A2.html
思路
* 零钱兑换:题目可转换为装满容量为amount的背包最少需要几个物品,每个物品可以有无数个
* dp[j] 表示装满容量为j的背包最少需要dp[j]个物品
* 那么对于第i个物品,如果不装,则依然有dp[j]个物品,如果装,dp[j-coins[i]]+1
* dp数组如何初始化
* 首先凑足总金额为0所需钱币的个数一定是0,那么dp[0] = 0;
* 其他下标对应的数值呢?
* 考虑到递推公式的特性,dp[j]必须初始化为一个最大的数,否则就会在min(dp[j - coins[i]] + 1, dp[j])比较的过程中被初始值覆盖。
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0; i < coins.length; i++) {
for (int j = coins[i]; j <= amount ; j++) {
dp[j] = Math.min(dp[j],dp[j-coins[i]] +1);
}
}
if (dp[amount] == Integer.MAX_VALUE)
return -1;
return dp[amount];
}
LeetCode 279.完全平方数
题目链接:https://leetcode.cn/problems/perfect-squares/description/
文章链接:https://programmercarl.com/0279.%E5%AE%8C%E5%85%A8%E5%B9%B3%E6%96%B9%E6%95%B0.html
思路
* 完全平方数:题目可转换为装满容量为n的背包至少需要几个完全平方数
public int numSquares(int n) {
int max = Integer.MAX_VALUE;
int[] dp = new int[n + 1];
//初始化
for (int j = 1; j <= n; j++) {
dp[j] = max;
}
for (int i = 1; i <= n ; i++) {
for (int j = i * i; j <= n ; j++) {
dp[j] = Math.min(dp[j], dp[j - i * i] + 1);
}
}
return dp[n];
}
LeetCode 139.单词拆分
题目链接:https://leetcode.cn/problems/word-break/description/
文章链接:https://programmercarl.com/0139.%E5%8D%95%E8%AF%8D%E6%8B%86%E5%88%86.html
思路
* 单词拆分:单词就是物品,字符串s就是背包,单词能否组成字符串s,就是问物品能不能把背包装满。
* 拆分时可以重复使用字典中的单词,说明就是一个完全背包!
* dp[i] : 字符串长度为i的话,dp[i]为true,表示可以拆分为一个或多个在字典中出现的单词。
* 如果确定dp[j] 是true,且 [j, i] 这个区间的子串出现在字典里,那么dp[i]一定是true。(j < i )。
* 所以递推公式是 if([j, i] 这个区间的子串出现在字典里 && dp[j]是true) 那么 dp[i] = true。
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (String word : wordDict) {
int len = word.length();
if (i >= len && dp[i-len] == true && word.equals(s.substring(i-len, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}