Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
一刷
题解:
这里依然是用了跟上一题目很接近的方法。不同的地方在于,每个数字不可以被无限次。所以一个数只能一次,而且遇到重复数字我们要跳过。这样需要先sort数组,在for循环里要加入一条 - if (i > pos && candidates[i] == candidates[i - 1]) continue; 并且在DFS的时候每次
每次新的position = i + 1, 并不是上一题的position = I。
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if(candidates == null || candidates.length == 0) return res;
Arrays.sort(candidates);
permutation(res, candidates, target, 0, new ArrayList<Integer>());
return res;
}
public void permutation(List<List<Integer>> res, int[] candidates, int target, int pos, List<Integer> list){
if(target == 0) {
res.add(new ArrayList<Integer>(list));
return;
}
if(target<0) return;
if(pos>candidates.length-1) return;
for(int i=pos; i<candidates.length; i++){
if (i > pos && candidates[i] == candidates[i - 1]) {
continue;
}
list.add(candidates[i]);
permutation(res, candidates, target - candidates[i], i+1, list);
list.remove(list.size()-1);
}
return;
}
}
二刷
DFS + backtracking
for循环中,剔除的情况是,if(i!=index && candidates[i] == candidates[i-1]) continue;
,因为在 candidates[i]的组合中,与candidates[i-1]的组合重合。(此时candidates[i-1]已经不在list中。
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
if(candidates == null || candidates.length == 0) return res;
Arrays.sort(candidates);
comb(res, list, 0, candidates, target);
return res;
}
private void comb(List<List<Integer>> res, List<Integer> list, int index, int[] candidates, int target){
if(target<0) return;
if(target == 0){
res.add(new ArrayList<>(list));
return;
}
for(int i = index; i<candidates.length; i++){
if(i!=index && candidates[i] == candidates[i-1]) continue;
list.add(candidates[i]);
comb(res, list, i+1, candidates, target-candidates[i]);
list.remove(list.size()-1);
}
}
}