[LeetCode] 40. 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.
  • 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]
]

Thought process:
Search for all subsets of C. For each subset, check if the numbers sum to T. If so, add it to the result list. I also need to skip duplicate combinations. Sort the array first. Looking at a number, if it's not the first number visited of current recurrence, and it's the same as its previous number, then it will create a duplicate if it's add to the combination.

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
25
26
27
28
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> combinations = new ArrayList<>();
        List<Integer> combination = new ArrayList<>();
        Arrays.sort(candidates);
        combinationSum2(candidates, target, 0, combination, combinations);
        return combinations;
    }
    
    private void combinationSum2(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++) {
            if (i > start && candidates[i] == candidates[i - 1]) {
                continue;
            }
            combination.add(candidates[i]);
            combinationSum2(candidates, target - candidates[i], i + 1, 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