提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
我们知道这是完全背包, 如果求组合数就是外层for循环遍历物品,内层for遍历背包。 如果求排列数就是外层for遍历背包,内层for循环遍历物品。
一、力扣518. 零钱兑换 II
在这里插入代码片class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount+1];
dp[0] = 1;
for(int i = 0; i < coins.length; i ++){
for(int j = 1; j <= amount; j ++){
if(j >= coins[i]){
dp[j] += dp[j-coins[i]];
}
}
}
return dp[amount];
}
}
二、力扣377. 组合总和 Ⅳ
class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target+1];
dp[0] = 1;
for(int i = 1; i <= target; i ++){
for(int j = 0; j < nums.length; j ++){
if(i >= nums[j]){
dp[i] += dp[i-nums[j]];
}
}
}
return dp[target];
}
}
三、力扣322. 零钱兑换
class Solution {
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 = 1; i <= amount; i ++){
for(int j = 0; j < coins.length; j ++){
if(i-coins[j] >= 0 && dp[i-coins[j]] != Integer.MAX_VALUE){
dp[i] = Math.min(dp[i-coins[j]]+1,dp[i]);
}
}
}
return dp[amount] == Integer.MAX_VALUE ? -1:dp[amount];
}
}
四、力扣279. 完全平方数
在这里插入代码片class Solution {
public int numSquares(int n) {
int[] dp = new int[n+1];
Arrays.fill(dp,Integer.MAX_VALUE);
dp[0] = 0;
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= 100; j ++){
if((i-j*j)<0){
continue;
}
dp[i] = Math.min(dp[i],dp[i-(j*j)]+1);
}
}
return dp[n];
}
}
875

被折叠的 条评论
为什么被折叠?



