[LeetCode] 39. Combination Sum

Given a set of candidate numbers (C(without duplicates) 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.
  • 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]
]

Thought process:
Search for all the subsets (including duplicates) of C. For each subset, check if the numbers sum to T. If so, add to result list.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> combinations = new ArrayList<>();
        List<Integer> combination = new ArrayList<>();
        combinationSum(candidates, target, 0, combination, combinations);
        return combinations;
    }
    
    private void combinationSum(int[] candidates, int target, int start, List<Integer> combination, List<List<Integer>> combinations) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            combinations.add(new ArrayList<>(combination));
            return;
        }
        
        for (int i = start; i < candidates.length; i++) {
            combination.add(candidates[i]);
            combinationSum(candidates, target - candidates[i], i, combination, combinations);
            combination.remove(combination.size() - 1);
        }
    }
}

Time complexity: O(n!).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula