当前位置:网站首页>完全背包问题求组合数和排列数
完全背包问题求组合数和排列数
2022-08-01 16:22:00 【北海冥鱼未眠】

这个是完全背包问题的典型应用,由于只是求个数,不涉及到零钱排列情况不一样算两次的情况,所以两层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];
}
}

这个与上面一题唯一不同的一点就是有序,顺序不同算两次,所以这里两层for循环的遍历顺序是外层遍历背包,内层遍历物品。
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];
}
}
关于背包问题,参考文章。
边栏推荐
猜你喜欢

A full review of mainstream timed task solutions

美国弗吉尼亚大学、微软 | Active Data Pattern Extraction Attacks on Generative Language Models(对生成语言模型的主动数据模式提取攻击)

DOM系列之触屏事件

MySQL data processing of authorization 】 【

14年测试人最近的面试经历,值得借鉴√

今晚直播!

如何有效地开发 Jmix 扩展组件

Vulnhub靶机:HARRYPOTTER_ NAGINI

js邯郸市地图网页源码下载

【Unity,C#】哨兵点位循迹模板代码
随机推荐
06 redis 集群搭建
2.8K 120Hz touch dual-screen blessing Lingyao X dual-screen Pro 2022 makes the office without fear of imagination
MySQL [create and manage tables]
intentservice使用(Intention)
等变图神经网络在药物研发中大放异彩
实习日报-2022-7-30
ESP8266-Arduino编程实例-74HC595位移寄存驱动
HashCode technology insider interview must ask
未来小间距竞争的着力点在哪里
Zhaoqi Science and Technology Innovation Platform attracts talents and attracts talents, and attracts high-level talents at home and abroad
五分钟带你上手ShardingJDBC实现MySQL分库分表
untiy Resorces目录动态加载资源
软件测试谈薪技巧:同为测试人员,为什么有人5K,有人 20K?
moxa串口服务器配置说明(moxa串口驱动)
时序数据库在船舶风险管理领域的应用
七夕专属博文-使用QGraphics画“红心“或“黑心“(含数学模型讲解)
5年测试,只会功能要求17K,功能测试都敢要求这么高薪资了?
年化收益高的理财产品
面试必问的HashCode技术内幕
蚂蚁首次披露核心基础软件技术开源版图