Leetcode-Combination Sum

LiBlog發表於2014-11-21

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 (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ 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]

Solution:

A recursive method.

 1 public class Solution {
 2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 3         List<List<Integer>> resSet = new ArrayList<List<Integer>>();
 4         List<Integer> curRes = new ArrayList<Integer>();
 5         if (candidates.length==0) return resSet;
 6         Arrays.sort(candidates);
 7         int cur=0,end=candidates.length-1;
 8         for (int i=0;i<candidates.length;i++)
 9             if (candidates[i]>target){
10                 end = i-1;
11                 break;         
12             }
13          
14 
15         sumRecur(candidates,cur,end,target,resSet,curRes);
16 
17         return resSet;
18     }
19 
20 
21     public void sumRecur(int[] candidates, int cur, int end, int valLeft, List<List<Integer>> resSet, List<Integer> curRes){
22         if (valLeft==0){
23             List<Integer> temp = new ArrayList<Integer>();
24             temp.addAll(curRes);
25             resSet.add(temp);
26             return;
27         }
28 
29         if (valLeft>= candidates[cur]){
30             curRes.add(candidates[cur]);
31             sumRecur(candidates,cur,end,valLeft-candidates[cur],resSet,curRes);
32             curRes.remove(curRes.size()-1);
33         }
34 
35         if (cur<end){
36             sumRecur(candidates,cur+1,end,valLeft,resSet,curRes);
37         }
38     }
39 }