题目所属分类
上一道题当作完全背包问题的话 那么这道题就是多重背包问题
限制每个数字出现的个数
原题链接
给定一个候选人编号的集合 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);
}
}
}