Every set of k distinct digits from 1 to 9 that sums to n: pick in increasing order, track what's left, and stop once a digit is too big.
▼The problem
LeetCode 216 (Medium). Find all combinations of k distinct numbers from 1 to 9 that add up to n; each number is used at most once, and every combination appears once.
Examples (LeetCode's): k = 3, n = 9 → [[1, 2, 6], [1, 3, 5], [2, 3, 4]] (the one walked through, all the way), and k = 4, n = 1 → [] (the four smallest already make 1 + 2 + 3 + 4 = 10).
The solution
def combination_sum3(k, n):
res, path = [], []
def go(start, left):
if len(path) == k:
if left == 0: res.append(path[:])
return
for d in range(start, 10):
if d > left: break
path.append(d)
go(d + 1, left - d)
path.pop()
go(1, n)
return resTranscript
Combination Sum Three. Pick k different numbers from one to nine that add up to n, each used at most once, and return every such combination.
Say k is three and n is nine. There are three answers: one, two, six; one, three, five; and two, three, four. But four numbers can never add up to one: the smallest four already make ten.
The slow way: try every group of k numbers and keep the ones with the right sum. For three, that's eighty-four groups, to find just three answers.
The key idea: build each group one number at a time, in increasing order, and track what's left of n. Going up means no group is built twice. With k picked, keep them if nothing is left. And since the numbers only grow, the moment one is bigger than what's left, so is every number after it: stop the whole loop.
Let's play k three, n nine. Pot the one: eight left. Pot the two: six left. The three leaves three, but the rack is full: put it back. The four and the five leave something too: back. The six leaves zero: record one, two, six. The seven is bigger than six: break. Back up and try one, three: one, three, five works. Then the twos give two, three, four, and the rest break almost at once. Thirty-two shots in all. Without the breaks, it would take a hundred and twenty-nine.
In code, a helper takes the next number to try and the amount left. When the path is full, record a copy if nothing is left. Otherwise, loop from start to nine, break when the number is too big, then push it, recurse with less left, and pop it.
At most nine choose k groups, a hundred twenty-six at worst, each copied in k steps. The recursion is only k deep, so the extra space is order k.
Pick in order, track what's left, break when it's too big. That's Combination Sum Three.