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.
public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if (candidates==null||candidates.length==0||target<=0) {
return lists;
}
Arrays.sort(candidates);
List<Integer> list = new ArrayList<Integer>();
getRes1(lists, list, candidates, target, 0);
return lists;
}
public static void getRes1(List<List<Integer>> lists,List<Integer> list,int[] arr,int target,int index) {
if (target>0) {
for (int i = index; i < arr.length; i++) {
if (i > index && arr[i] == arr[i-1]) continue;
list.add(arr[i]);
getRes1(lists, list, arr, target-arr[i], i+1);
list.remove(list.size()-1);
}
} else if (target==0) {
lists.add(new ArrayList<Integer>(list));
}
}