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] ]
本来想着用Set来去除重,结果TLE啦。那只能在递归中的for循环里面去重了。
public class Solution {
private void helper(int[] candidates, int pos, int target, Stack<Integer> stack, List<List<Integer>> list){
if(target < 0) return ;
if(target == 0){
List<Integer> row = new ArrayList<>();
for(int i:stack){
row.add(i);
}
list.add(row);
return;
}
int prev = 0;
for(int i=pos; i<candidates.length; i++){
if(candidates[i] == prev) continue;
prev =candidates[i];
stack.push(candidates[i]);
helper(candidates, i+1, target-candidates[i], stack, list);
stack.pop();
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Stack<Integer> stack = new Stack<>();
List<List<Integer>> lists = new ArrayList<>();
Arrays.sort(candidates);
helper(candidates, 0, target, stack, lists);
return lists;
}
}