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, compare with 37!!!

---

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) {

        
        // found!
        if (target == 0) { 
            // copy
            ArrayList<Integer> l = new ArrayList<Integer>(list);
            rst.add(l);
            return;
        } 
        
        // check
        if (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-15 10:10  LEDYC  阅读(179)  评论(0)    收藏  举报