leetcode 40. 组合总和 II-java
题目所属分类
上一道题当作完全背包问题的话 那么这道题就是多重背包问题
限制每个数字出现的个数
原题链接
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
代码案例:输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
题解
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates,0,target);
return res;
}
public void dfs(int[] c , int u , int target){
if(target == 0){
res.add(new ArrayList(path));
return ;
}
if(u == c.length) return;
//找到每个的个数 当前的是u
int k = u+ 1 ;
while(k < c.length &&c[k] == c[u]) k++;
int cnt = k - u ;//每个数的个数为cnt
for(int i = 0; c[u]*i <= target && i <=cnt ;i++ ){
dfs(c,k,target-c[u]*i);//下端的第一个是k
path.add(c[u]);
}
//恢复现场
for(int i= 0 ; c[u]* i <=target && i <=cnt ; i++){
path.remove(path.size()-1);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)