39. Combination Sum II

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 (a1a2, � , 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
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

---

check dup

check target ==0 first!!!

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
        Arrays.sort(num);
        
        ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        helper(num, 0, target, list, rst);
        return rst;
    }

    private void helper(int[] arr, int index, int target, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> rst) {
        
        if (target == 0) { // Done
            ArrayList<Integer> l = new ArrayList<Integer>(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);
        }
        
    }
}

 

posted @ 2013-09-22 11:27  LEDYC  阅读(161)  评论(0)    收藏  举报