#216

Combination Sum III

Medium
ArrayBacktrackingBacktrackingCombination Generation
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

We can use backtracking to build combinations incrementally. This approach is more efficient as it avoids unnecessary checks by pruning paths that exceed the target sum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a backtracking function that takes the current combination, current sum, and the next number to consider.
  2. 2Step 2: If the combination length equals k and the sum equals n, add it to the result.
  3. 3Step 3: Iterate through the numbers from the current number to 9, adding each to the combination and recursing.
solution.py15 lines
1def combinationSum3(k, n):
2    def backtrack(start, path, target):
3        if len(path) == k and target == 0:
4            result.append(path[:])
5            return
6        for i in range(start, 10):
7            if i > target:
8                break
9            path.append(i)
10            backtrack(i + 1, path, target - i)
11            path.pop()
12
13    result = []
14    backtrack(1, [], n)
15    return result

Complexity note: The time complexity is O(n) because we effectively explore combinations without generating all possible subsets, pruning paths that exceed the target.

  • 1Backtracking allows us to explore combinations efficiently by pruning invalid paths early.
  • 2Using a range of 1 to 9 ensures we don't have duplicates and simplifies our checks.

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