Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.
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] ]
先将数组排序,再用回溯法
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> set=new LinkedList<>();
LinkedList<Integer> list=new LinkedList<>();
Arrays.sort(candidates);
helper(candidates,target,0,set,list);
return new LinkedList<>(set);
}
public void helper(int[] nums,int k,int index,List<List<Integer>> set,LinkedList<Integer> list){
if(k==0){
set.add(new LinkedList<>(list));
return;
}
if(k<0)
return;
for(int i=index;i<nums.length;i++){
if(i>index&&nums[i-1]==nums[i]) continue;
list.add(nums[i]);
helper(nums,k-nums[i],i+1,set,list);
list.removeLast();
}
}
}