当前位置:网站首页>Complete knapsack problem to find the number of combinations and permutations
Complete knapsack problem to find the number of combinations and permutations
2022-08-01 16:32:00 【North Sea ghost fish not sleeping】

This is a typical application of the complete knapsack problem,Because it's just asking for numbers,It does not involve the case where the arrangement of the change is different and counted twice,所以两层for循环,外层遍历物品,内层遍历背包.
class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount+1];
dp[0] = 1;
for (int coin : coins) {
for (int i = coin;i<= amount;i++){
dp[i] += dp[i-coin];
}
}
return dp[amount];
}
}

The only difference between this one and the one above is the ordering,Different order counts twice,So here are two layersforThe traversal order of the loop is 外层遍历背包,内层遍历物品.
class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target+1];
dp[0] = 1;
for(int j = 1;j<=target;j++){
for(int i = 0;i<nums.length;i++){
if(j>=nums[i]) dp[j] += dp[j-nums[i]];
}
}
return dp[target];
}
}
关于背包问题,参考文章.
边栏推荐
猜你喜欢
随机推荐
Convert tensor to image in pytorch
【Untitled】
90后的焦虑,被菜市场治好了
ECCV 2022 | Poseur:你以为我是姿态估计,其实是目标检测哒
软件测试谈薪技巧:同为测试人员,为什么有人5K,有人 20K?
MySQL data processing of authorization 】 【
MUI 做手机返回操作栏
PHP 安全漏洞:会话劫持、跨站点脚本、SQL 注入以及如何修复它们
C#的CSV格式文件帮助类
pytorch中tensor转成图片保存
27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
MUI as a mobile phone to return to the action bar
提速!进口婴幼儿配方产品出证仅需1-3天
【Unity,C#】哨兵点位循迹模板代码
A full review of mainstream timed task solutions
MLX90640 红外热成像仪测温模块开发笔记(完整版)
DOM树jsjs特效代码
OpenCV-resize函数「建议收藏」
好家伙,公司服务器直接热崩掉了!
清华教授发文劝退读博:我见过太多博士生精神崩溃、心态失衡、身体垮掉、一事无成!...







