LeetCode #216 Medium

Combination Sum III

Combination Sum III is LeetCode 216 (Medium). Find every combination of exactly k numbers that add up to n, where:

  • only the digits 1 to 9 may be used, and
  • each digit appears at most once in a combination.

Return the combinations in any order, with no combination listed twice. There is no input array: the pool is always the nine digits, so the search is tiny whatever k and n are.

Constraints
  • 2 <= k <= 9
  • 1 <= n <= 60
backtrackingrecursioncombinatoricspruning
Open on LeetCode ↗
02

Intuition

Build each combination in increasing order, one digit per slot, so every set of digits is produced exactly once. A combination is finished only when both counts close together: k slots filled and the remaining sum at 0.

The useful cut looks ahead. Suppose need slots are still empty and you are about to try digit d. The cheapest way to fill them is d, d + 1, …, d + need − 1. If even that smallest finish is bigger than the remaining sum, no digit from d upward can work, so stop the loop. Every larger digit only makes the finish bigger.

How to spot this pattern

Fixed size plus fixed sum over a tiny pool, with every answer listed: a backtracking search over increasing digits, as in Combinations (77), with a sum added.

03

Approach

Try it first

Before reading on, try k = 3 and n = 7 by hand. After taking 1 and 3, can any third digit work? How could you know that before trying one?

1

Fill slots with increasing digits

Write dfs(start, remain), where start is the smallest digit still allowed and remain is what the empty slots must add up to. After taking digit d, call dfs(d + 1, remain - d). Each digit is used once, and every combination comes out in sorted order, so none is repeated.

2

Check both counts when the slots are full

When the path holds k digits, save a copy only if remain is 0, then return either way. Returning here also stops a path from ever growing past k digits.

3

Stop once the smallest finish is too big

With need empty slots, the smallest sum digit d can start is need · d + need · (need − 1) / 2, the total of d up to d + need − 1. If that is above remain, break out of the loop. This also covers the plain case d > remain, which is that test with one slot left.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def combinationSum3(self, k: int, n: int) -> List[List[int]]:
▶3 res, path = [], []
▶4 
▶5 def dfs(start: int, remain: int) -> None:
▶6 need = k - len(path)
▶7 if need == 0:
▶8 if remain == 0:
▶9 res.append(path[:])
▶10 return
▶11 for d in range(start, 10):
▶12 smallest = need * d + need * (need - 1) // 2
▶13 if smallest > remain:
▶14 break
▶15 path.append(d)
▶16 dfs(d + 1, remain - d)
▶17 path.pop()
▶18 
▶19 dfs(1, n)
▶20 return res
digits1234567893 slots++left7smallest finishnot tried yetanswersnone yetfill 3 slots with digits that add up to 7
k3digits to choose
n7their sum
Each slot gets a digit larger than the one before it, so every set of digits is built once, in increasing order. Before a digit goes in, the cheapest way to fill the remaining slots from that digit is checked against what is left.
digits1take234567893 slots1++left6smallest finish1+2+3=6≤7answersnone yetsmallest finish 6 fits in 7 → take 1
path[1]
left6
Even the cheapest finish from 1, 1 + 2 + 3 = 6, fits in 7, so a combination starting this way may exist. Put 1 in slot 1; the next slot may only use digits above 1.
digits12take34567893 slots1+2+left4smallest finish2+3=5≤6answersnone yetsmallest finish 5 fits in 6 → take 2
path[1, 2]
left4
Even the cheapest finish from 2, 2 + 3 = 5, fits in 6, so a combination starting this way may exist. Put 2 in slot 2; the next slot may only use digits above 2.
digits123take4567893 slots1+2+3left1smallest finish3≤4answersnone yettake 3 → slots full, 1 short
path[1, 2, 3]
left1
Digit 3 fits in the 4 left, so it goes in the last slot. Now all 3 slots are used, yet the digits add up to only 6. No slot is free for the missing 1, so this branch ends. The next, larger digit is tried in the last slot instead.
digits1234take567893 slots1+2+4left0smallest finish4≤4answers124take 4 → 1 + 2 + 4 = 7 → save it
saved[1, 2, 4]
The last slot needs exactly 4, and 4 is it. Both counts close on the same step: all 3 slots are filled and nothing is left to reach. A copy of [1, 2, 4] goes into the answers.
digits12345stop67893 slots1+2+left4smallest finish5>4answers1245 is more than 4 → stop
digit5
smallest finish55
left4
The one empty slot would need a digit of at most 4, and 5 is bigger. Every larger digit only costs more, so the loop stops here instead of trying 5 to 9.
digits123stop4567893 slots1++left6smallest finish3+4=7>6answers124smallest finish 7 is more than 6 → stop
digit3
smallest finish73 + 4
left6
Starting at 3, the 2 empty slots cost at least 3 + 4 = 7, which is more than the 6 left. Every larger digit only costs more, so the loop stops here instead of trying 3 to 9.
digits12stop34567893 slots++left7smallest finish2+3+4=9>7answers124smallest finish 9 is more than 7 → stop
digit2
smallest finish92 + 3 + 4
left7
Starting at 2, the 3 empty slots cost at least 2 + 3 + 4 = 9, which is more than the 7 left. Every larger digit only costs more, so the loop stops here instead of trying 2 to 9.
digits1234567893 slots++left7smallest finishnot tried yetanswers124done → 1 combination saved
result[[1, 2, 4]]
The search is over. Every saved combination has exactly 3 different digits adding up to 7, and each appears once because digits always went in increasing order.
05

Common pitfalls

Saving as soon as the sum reaches 0

✗ Wrong
if remain == 0:
    res.append(path[:])
    return
✓ Right
if len(path) == k:
    if remain == 0:
        res.append(path[:])
    return

Short paths that already add up to n slip in. With the plain d > remain cut, k = 3 and n = 9 gives [9], [1, 8], [2, 7], [3, 6] and [4, 5] saved next to the three real answers.

06

Edge cases

n is too small for k digits, e.g. k = 4, n = 1

The smallest four digits add up to 1 + 2 + 3 + 4 = 10, so the very first check fails and [] comes back without any recursion.

n is too big for k digits, e.g. k = 2, n = 18

The largest pair is 9 + 8 = 17. The look-ahead only cuts sums that are too small, so the search tries the pairs and every one ends with a remainder, giving []. Only C(9, 2) = 36 pairs exist, so this is still instant.

07

Complexity

Time
O(C(9, k) · k)
Space
O(k)
At most C(9, k) sets of k digits exist (126 at most, for k = 4 or 5), and saving one copies k digits. Space is the recursion depth and the path, which never go past k.
08

Combination Sum III FAQ

How is it different from Combination Sum II?

Combination Sum II takes an input array with repeated values and no size limit, so it needs a skip for equal neighbours. Here the pool is fixed at the digits 1 to 9 with no repeats, but the answer must have exactly k numbers.

Can the combinations be found with a bitmask instead?

Yes. Each of the 512 masks from 0 to 511 picks a subset of the nine digits; keep the masks with exactly k bits set whose digits add up to n. It is short and correct, but it checks every subset, while the search above stops at the first digit that cannot fit.

Why not prune when the largest finish is too small as well?

It is valid: if the need largest unused digits cannot reach remain, the branch is dead. With only nine digits the search is already tiny, so one cut keeps the code short; add the other if the pool were much larger.