题目描述:
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
输入:
candidates = [10,1,2,7,6,1,5], target = 8
candidates = [2,5,2,1,2], target = 5
输出:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
[
[1,2,2],
[5]
]
题意:
题目描述
题解:
排个序,然后相邻判断一下就直接dfs
代码:
class Solution {
public List<List<Integer>> result = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
if(candidates.length == 0){
return result;
}
Arrays.sort(candidates);
comSum2(candidates,target,0,new LinkedList<Integer>());
return result;
}
public void comSum2(int[] candidates, int target, int index, LinkedList<Integer> trace){
if(target == 0){
result.add(new LinkedList(trace));
return ;
}
if(target > 0){
for(int i = index; i<candidates.length; i++){
if(i > index && candidates[i] == candidates[i - 1]) continue;
trace.add(candidates[i]);
comSum2(candidates,target - candidates[i],i+1,trace);
trace.removeLast();
}
}
}
}