Combination Sum III (LeetCode 216): Solution and Explanation

Medium
Array
Backtracking

Find every set of exactly k distinct digits from 1 through 9 whose values add up to n. Each digit can appear at most once in a combination, and the order of digits inside a combination does not matter, so [1,2,4] and [4,2,1] count as the same answer.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Because the pool of candidates is tiny, the brute force is genuinely possible: there are only 2⁹ = 512 subsets of the digits 1 through 9. You could enumerate every subset, keep those with exactly k elements and the right sum, and return them. That is already fast, so the real lesson here is how to structure the search cleanly so it scales to the harder members of the combination family.

The standard structure is backtracking with a start index. You build a combination one digit at a time, and each recursive call only considers digits larger than the last one you picked. That single rule removes duplicates like [2,1,4] versus [1,2,4] for free, because every combination is generated in increasing order exactly once.

The other ingredient is pruning. You carry the remaining sum down the recursion, and you stop a branch as soon as it has k digits or the remaining sum goes negative. A branch that already holds k digits can only succeed if the remaining sum is exactly zero, so that check doubles as the success condition.

Approach: Backtracking with a start index

  1. Create an empty result list and a recursive helper backtrack(start, path, remaining).
  2. If path has k digits and remaining is 0, append a copy of path to result and return.
  3. If path already has k or more digits, or remaining is negative, return, because this branch cannot produce a valid answer.
  4. Otherwise loop i from start to 9. Append i, recurse with start = i + 1 and remaining - i, then pop i to undo the choice.
  5. Kick off the search with backtrack(1, [], n) and return result.

Step-by-step example

k = 3, n = 7
  1. The search starts with path = [] and remaining = 7. It picks 1, leaving 6, then picks 2, leaving 4.
  2. With [1,2] it tries 3: the path [1,2,3] has three digits but 1 is left over, so that branch returns without recording anything.
  3. Next it tries 4: [1,2,4] has three digits and remaining is exactly 0, so a copy is added to result.
  4. Trying 5 through 9 after [1,2] drives remaining negative, so each of those calls returns immediately.
  5. Branches such as [1,3], [1,4] and [2,3] cannot be completed: [1,3,4] needs 8 and [2,3,4] needs 9, both above 7. The final answer is [[1,2,4]].

Code: Python, Java, C++

1class Solution:
2    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
3        result = []
4
5        def backtrack(start, path, remaining):
6            if len(path) == k and remaining == 0:
7                result.append(path[:])
8                return
9            if len(path) >= k or remaining < 0:
10                return
11
12            for i in range(start, 10):
13                path.append(i)
14                backtrack(i + 1, path, remaining - i)
15                path.pop()
16
17        backtrack(1, [], n)
18        return result

Time and space complexity

Time

O(C(9, k) × k)

The recursion only ever explores increasing sequences of distinct digits, so it visits at most the 512 subsets of 1 through 9, and each recorded answer costs O(k) to copy. In practice this is bounded by a small constant because the digit pool never grows.

Space

O(k)

The recursion depth and the working path never exceed k digits, which is at most 9. The output list is not counted as extra space.

Other approaches

Bitmask enumeration (time O(2⁹ × 9), space O(1))

Loop over every mask from 0 to 511, keep masks with exactly k set bits whose digit sum equals n, and convert them to lists. It has no recursion and is easy to get right, but it always checks all 512 masks with no pruning.

Common mistakes

  • Reusing digits. Recursing with start = i instead of i + 1 lets the same digit appear twice, which this problem forbids.
  • Appending path itself instead of a copy. Every entry in result then points at the same list and ends up empty after backtracking undoes the choices.
  • Looping up to range(start, 9) and silently excluding the digit 9. The upper bound must be 10 in Python.
  • Not pruning on a negative remainder. The code still works without it, but the search then wanders through many hopeless branches; breaking out of the loop once i > remaining is an easy extra speedup.

Frequently asked questions

What is the difference between Combination Sum, II and III?

The first lets you reuse each candidate any number of times, the second gives a list with duplicates where each element is used once, and the third fixes the pool to the digits 1 through 9 and also fixes the combination size to k. All three use the same backtracking skeleton with small changes to the start index and duplicate handling.

What is the time complexity of Combination Sum III?

It is bounded by the number of subsets of nine digits, so at most 512 search states plus O(k) per recorded answer. That makes it effectively constant time, which is why the constraints are so relaxed.

Why don't I need a visited set to avoid duplicate combinations?

Each call only considers digits larger than the last one chosen, so every combination is built in strictly increasing order. A given set of digits has exactly one increasing order, so it can only be generated once.

What happens when n is larger than 45?

The largest possible sum uses all nine digits and equals 45, so any larger n has no solution and the function returns an empty list after a short search.