Tuesday, May 26, 2015

[LeetCode] Combination Sum

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] 
Hashtags:  Array Backtracking



Solution: We first sort the array (for the 2nd constraint in the problem description).
For the 1st element a, we use 0, 1, ...., t number of a's, where t = target / a. Then we solve the problem recursively using the remaining n - 1 elements and updated target value. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Solution {
    private List<List<Integer>> combinationSum(
        int[] candidates, 
        int i,
        int target
    ) {
        ArrayList<List<Integer>> list = 
            new ArrayList<List<Integer>>();
        if (i >= candidates.length) {
            return list;
        }
        
        int val = candidates[i];
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        for (int j = 0; j <= target / val; j++) {
            int new_target = target - j * val;
            if (new_target == 0) {
                list.add(tmp);
                continue;
            }
            List<List<Integer>> ll = combinationSum(
                                         candidates, 
                                         i + 1, 
                                         new_target
                                     );
            for (List<Integer> li : ll) {
                ArrayList<Integer> l = new ArrayList<Integer>(tmp);
                l.addAll(li);
                list.add(l);
            }
            tmp.add(val);
        }
        return list;
    }
    
    public List<List<Integer>> combinationSum(
        int[] candidates, 
        int target
    ) {
        Arrays.sort(candidates);
        return combinationSum(candidates, 0, target);
    }
}

No comments:

Post a Comment