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:
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 ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
Arrays.sort(num) ;
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
combination2(num, target, 0, 0, temp, result);
return result;
}
private void combination2(int[] candidates, int target, int sum, int start, ArrayList<Integer> combin, ArrayList<ArrayList<Integer>> result) {
//check add
if(sum > target) return;
if(sum == target) {
result.add(combin);
return;
}
for(int i = start; i < candidates.length; i++) {
ArrayList<Integer> temp = new ArrayList<Integer>(combin);
temp.add(candidates[i]);
combination2(candidates, target, sum + candidates[i], i + 1, temp, result);
while(i < candidates.length - 1 && candidates[i] == candidates[i + 1]) i++;
}
}