#39

Combination Sum

Medium
ArrayBacktrackingBacktrackingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n^target/min(candidates))
O(n^target/min(candidates))
Space
O(target/min(candidates))
O(target/min(candidates))
💡

Intuition

Time O(n^target/min(candidates))Space O(target/min(candidates))

The optimal solution uses backtracking efficiently by avoiding unnecessary paths. It builds combinations incrementally and only continues if the current total does not exceed the target.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a result list and a backtracking function.
  2. 2Step 2: In the backtracking function, if the current total equals the target, add the current path to the result.
  3. 3Step 3: Loop through the candidates, and for each candidate, if adding it to the total does not exceed the target, recursively call the backtracking function.
solution.py11 lines
1def combinationSum(candidates, target):
2    def backtrack(start, path, total):
3        if total == target:
4            result.append(path)
5            return
6        for i in range(start, len(candidates)):
7            if total + candidates[i] <= target:
8                backtrack(i, path + [candidates[i]], total + candidates[i])
9    result = []
10    backtrack(0, [], 0)
11    return result

Complexity note: The optimal solution has the same time complexity as the brute force but is more efficient in practice due to pruning unnecessary paths. The space complexity remains the same due to the depth of recursion.

  • 1Backtracking allows us to explore all combinations while pruning paths that exceed the target.
  • 2Using recursion helps manage the state of combinations easily.

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