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.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- 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]
public class Solution {
List<List<Integer>> res;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
res = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
for (int i = 0; i < candidates.length; i++) {
List<Integer> list = new ArrayList<Integer>();
helper(candidates, list, i, 0, target);
while(i < candidates.length-1 && candidates[i] == candidates[i+1]) i++;
}
return res;
}
public void helper(int[] candidates, List<Integer> list, int pos, int sum, int target) {
sum += candidates[pos];
if (sum > target) return;
else if (sum == target) {
list.add(candidates[pos]);
List<Integer> tmp = new ArrayList<Integer>(list);
res.add(tmp);
list.remove(list.size()-1);
return;
}
else {
list.add(candidates[pos]);
int tPos = pos;
for (int i = pos+1; i < candidates.length; i++) {
helper(candidates, list, i, sum, target);
while(i < candidates.length-1 && candidates[i] == candidates[i+1]) i++;
}
list.remove(list.size()-1);
}
}
}