38. Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

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 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

---

典型recursive

---

 

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

    private void helper(int[] arr, int index, int target, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> rst) {
        
        if (index < 0 || index >= arr.length || target < 0)
            return;

        if (target == 0) { // Done
            ArrayList<Integer> l = new ArrayList<Integer>(list);
            rst.add(l);
            return;
        } 
        
        
        for (int i = index; i < arr.length; ++i) {
        
            if (arr[i] > target)    break;
        
            list.add(arr[i]);
            helper(arr, i, target - arr[i], list, rst);
            list.remove(list.size() - 1);
        }
        
    }
}
posted @ 2013-09-04 11:36  LEDYC  阅读(186)  评论(0)    收藏  举报