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
,
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
---
check dup
check target ==0 first!!!
public class Solution { public ArrayList> combinationSum2(int[] num, int target) { Arrays.sort(num); ArrayList > rst = new ArrayList >(); ArrayList list = new ArrayList (); helper(num, 0, target, list, rst); return rst; } private void helper(int[] arr, int index, int target, ArrayList list, ArrayList > rst) { if (target == 0) { // Done ArrayList l = new ArrayList (list); rst.add(l); return; } if (index < 0 || index >= arr.length || target < 0) return; for (int i = index; i < arr.length; ++i) { if (arr[i] > target) break; // check dup if(i>index && arr[i]==arr[i-1]) continue; list.add(arr[i]); helper(arr, i+1, target - arr[i], list, rst); list.remove(list.size() - 1); } }}