LeetCode #216 Medium

Combination Sum III

Find all combinations of exactly k distinct digits from 1 to 9 that sum to n.

backtrackingrecursioncombinatoricspruning
Open on LeetCode ↗
02

Intuition

💡

Coming off Combination Sum I and II you will track the remaining target and record a hit the moment it reaches zero. That is half a solution, and the half you dropped is the one this problem is built around. There are two constraints running at once — exactly k numbers AND a total of exactly n — and a path satisfying one is worthless without the other. For k=3, n=9 the path [9] sums perfectly and is not an answer, because it holds one digit instead of three; the path [1,2,3] has the right length and sums to 6, also not an answer. So the base case must test both together: you are done only when the path length hits k and the remainder hits zero on the same step. Everything else is a failure, including the near-misses. The same doubling applies to pruning — you can stop early when a digit already exceeds the remainder, and because the pool 1..9 is scanned in increasing order, no later digit can fit either, so you break out of the loop entirely rather than continuing. The invariant is that at every node, the path holds distinct increasing digits and remain equals n minus their sum, so both constraints stay exactly measurable without a rescan.

03

Approach

1

Track length and remainder together

Carry both the running path and the remaining sum through the recursion. The base case fires when the path reaches length k; only then do you check whether the remainder is zero. Recording on remainder == 0 alone accepts short paths, and checking length alone accepts wrong sums — the two tests belong in one place so neither can be forgotten.

2

Use a start index for distinctness and order

The pool is 1 through 9 and each digit may be used at most once, so a level that picks i recurses from i+1. This gives distinctness and increasing order for free, which in turn means [1,2,4] is generated once rather than in all six orderings. Same forward-only trick as Combinations 77, doing double duty here.

3

Prune on both constraints

Break out of the loop as soon as the candidate digit exceeds the remaining sum, since the pool only grows from there and every later digit fails too. You can prune harder still — if the largest achievable sum from the digits left cannot reach the remainder, or the smallest already overshoots, the subtree is dead. With a pool this small the first break is enough, but the habit of pruning on every constraint you are tracking is what generalises.

04

Solution & live demo

python
1class Solution:
2 def combinationSum3(self, k: int, n: int) -> list[list[int]]:
3 res, path = [], []
4 
5 def backtrack(start: int, remain: int) -> None:
6 if len(path) == k:
7 # BOTH constraints must close on the same step
8 if remain == 0:
9 res.append(path[:])
10 return
11 for d in range(start, 10):
12 if d > remain:
13 break
14 path.append(d)
15 backtrack(d + 1, remain - d)
16 path.pop()
17 
18 backtrack(1, n)
19 return res
05

Edge cases

n is smaller than the minimum possible sum, e.g. k=4, n=1

The smallest four distinct digits total 10, so the first-digit prune fires immediately and an empty list is returned without recursing.

n is larger than the maximum possible sum, e.g. k=2, n=30

No pair reaches 30; every path fills its k slots with a non-zero remainder, all are rejected at the base case, and the result is empty.

Exactly one valid combination, e.g. k=3, n=7

Only [1,2,4] satisfies both constraints; every other length-3 path is rejected for a wrong sum.

k = 9

The only possibility is all nine digits summing to 45, so the answer is [[1..9]] when n is 45 and empty otherwise.

06

Complexity

Time
O(C(9,k) * k)
Space
O(k)
The pool is fixed at nine digits, so the search space is bounded by 2^9 regardless of n — this is effectively constant work with a k-deep stack.