#40

Combination Sum II

Medium
ArrayBacktrackingBacktrackingSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * 2^n)
Space
O(1)
O(n)
💡

Intuition

Time O(n * 2^n)Space O(n)

The optimal solution uses backtracking to build combinations incrementally. By sorting the candidates and skipping duplicates, we efficiently explore valid combinations without generating all possible ones.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the candidates array to facilitate skipping duplicates.
  2. 2Step 2: Use a backtracking function to explore combinations, adding elements to the current combination.
  3. 3Step 3: If the sum of the current combination equals the target, add it to the result.
  4. 4Step 4: Skip duplicates by checking if the current element is the same as the previous one.
solution.py15 lines
1def combinationSum2(candidates, target):
2    candidates.sort()
3    result = []
4    def backtrack(start, path, target):
5        if target == 0:
6            result.append(path)
7            return
8        for i in range(start, len(candidates)):
9            if i > start and candidates[i] == candidates[i - 1]:
10                continue
11            if candidates[i] > target:
12                break
13            backtrack(i + 1, path + [candidates[i]], target - candidates[i])
14    backtrack(0, [], target)
15    return result

Complexity note: The time complexity is O(n * 2^n) due to the nature of backtracking, where each candidate can either be included or excluded. The space complexity is O(n) for the recursion stack and the result storage.

  • 1Sorting the candidates helps in skipping duplicates efficiently.
  • 2Backtracking allows us to explore combinations without generating all possible ones.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.