322. 零钱兑换
如果求组合数就是外层for循环遍历物品,内层for遍历背包。
如果求排列数就是外层for遍历背包,内层for循环遍历物品。
这句话结合本题 大家要好好理解。
视频讲解:https://www.bilibili.com/video/BV14K411R7yv
https://programmercarl.com/0322.%E9%9B%B6%E9%92%B1%E5%85%91%E6%8D%A2.html
class Solution {
public int coinChange(int[] coinValues, int totalAmount) {
int impossible = Integer.MAX_VALUE;
int[] minCoins = new int[totalAmount + 1];
for (int i = 0; i < minCoins.length; i++) {
minCoins[i] = impossible;
}
minCoins[0] = 0;
for (int i = 0; i < coinValues.length; i++) {
for (int j = coinValues[i]; j <= totalAmount; j++) {
if (minCoins[j - coinValues[i]] != impossible) {
minCoins[j] = Math.min(minCoins[j], minCoins[j - coinValues[i]] + 1);
}
}
}
return minCoins[totalAmount] == impossible ? -1 : minCoins[totalAmount];
}
}
279.完全平方数
本题 和 322. 零钱兑换 基本是一样的,大家先自己尝试做一做
视频讲解:https://www.bilibili.com/video/BV12P411T7Br
https://programmercarl.com/0279.%E5%AE%8C%E5%85%A8%E5%B9%B3%E6%96%B9%E6%95%B0.html
class Solution {
public int numSquares(int target) {
int impossible = Integer.MAX_VALUE;
int[] combinations = new int[target + 1];
for (int j = 0; j <= target; j++) {
combinations[j] = impossible;
}
combinations[0] = 0;
for (int sum = 1; sum <= target; sum++) {
for (int i = 1; i * i <= sum; i++) {
combinations[sum] = Math.min(combinations[sum], combinations[sum - i * i] + 1);
}
}
return combinations[target];
}
}
139.单词拆分
视频讲解:https://www.bilibili.com/video/BV1pd4y147Rh
https://programmercarl.com/0139.%E5%8D%95%E8%AF%8D%E6%8B%86%E5%88%86.html
import java.util.List;
class Solution {
public boolean wordBreak(String sentence, List<String> dictionary) {
boolean[] canBreak = new boolean[sentence.length() + 1];
canBreak[0] = true;
for (int index = 1; index <= sentence.length(); index++) {
for (String word : dictionary) {
int wordLength = word.length();
if (index >= wordLength && canBreak[index - wordLength] && word.equals(sentence.substring(index - wordLength, index))) {
canBreak[index] = true;
break;
}
}
}
return canBreak[sentence.length()];
}
}
关于多重背包,你该了解这些!
https://programmercarl.com/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80%E5%A4%9A%E9%87%8D%E8%83%8C%E5%8C%85.html
背包问题总结篇!
https://programmercarl.com/%E8%83%8C%E5%8C%85%E6%80%BB%E7%BB%93%E7%AF%87.html