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
A solution set is:
10,1,2,7,6,1,5
and target 8
,A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Solution:
Classic recursion problem.
Almost the same as last problem Combination Sum
Difference:
1. Element can only be used once and may have duplicated elements.
Tips:
1. The index for next level will be current index+1;
2. To avoid duplicated results: make sure if the iteration pointer i is not the start index, it will skip the duplicated element. Note: always execute the first loop(i==start).
eg. 2,2,2,3 target =7, the recursion tree will look like this:
2,2,2,3--> 2,2,3 --> 2,3, Notice: during the recursion, we skipped several 2,2,3 and 2,3
1. Element can only be used once and may have duplicated elements.
Tips:
1. The index for next level will be current index+1;
2. To avoid duplicated results: make sure if the iteration pointer i is not the start index, it will skip the duplicated element. Note: always execute the first loop(i==start).
eg. 2,2,2,3 target =7, the recursion tree will look like this:
2,2,2,3--> 2,2,3 --> 2,3, Notice: during the recursion, we skipped several 2,2,3 and 2,3
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(candidates==null || candidates.length==0) return res;
Arrays.sort(candidates);
List<Integer> item=new ArrayList<Integer>();
helper(candidates,0,target,item,res);
return res;
}
public void helper(int[] candidates, int index, int target, List<Integer> item, List<List<Integer>> res){
if(target==0){
List<Integer> temp= new ArrayList<Integer>(item);
res.add(temp);
return;
}
for(int i=index;i<candidates.length;i++){
if(target-candidates[i]<0) return;
item.add(candidates[i]);
helper(candidates,i+1,target-candidates[i],item,res);
item.remove(item.size()-1);
while(i<candidates.length-1 && candidates[i]==candidates[i+1]) i++;
}
}
doesn't work at all
ReplyDeleteModified, should work now.
Deleteshould be i+1 when calling recursive method
ReplyDeleteYes, you are right. Modified.
Delete