Pick exactly k different digits from 1 to 9 so that they add up to n. Each digit may appear at most once in a pick.
Return every such pick. Each pick is a list of its digits, and no pick may appear twice: [2, 3] and [3, 2] count as the same one. The picks can come back in any order.
Example 1
Input: k = 2, n = 5 Output: [[1, 4], [2, 3]] Why: 1 + 4 = 5 and 2 + 3 = 5; no other pair works
2 more examples and the constraints
Example 2
Input: k = 3, n = 8 Output: [[1, 2, 5], [1, 3, 4]] Why: the only two sets of three digits with sum 8
Example 3
Input: k = 3, n = 5 Output: [] Why: three digits add up to at least 1 + 2 + 3 = 6
Constraints
- 2 ≤ k ≤ 9
- 1 ≤ n ≤ 60
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check all 512 subsetsO(2⁹ · 9)
- Backtracking with an early stopO(C(9, k) · k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Subsets or calls looked at for k = 3, n = 9 | Verdict |
|---|---|---|---|
| Check all 512 subsets | O(2⁹ · 9) | Passes; the pool is tiny | |
| Backtracking with an early stop | O(C(9, k) · k) | Best; skips hopeless branches |
k = digits per pick; C(9, k) = ways to choose k of the 9 digits.
Edge cases to test
- n too small. k = 3, n = 5: the smallest three digits already sum to 6, so the answer is [].
- n too large. k = 2, n = 18: the largest pair is 8 + 9 = 17, so the answer is [].
- All nine digits. k = 9 works only for n = 45, giving [[1, 2, 3, 4, 5, 6, 7, 8, 9]].
- Exactly one pick. k = 2, n = 17 gives only [[8, 9]].
Common mistakes
- Letting the next digit start at 1 again, which produces [2, 3] and [3, 2] as two answers.
- Appending
pathitself instead of a copy, so every saved pick changes later. - Saving a path whose sum is n but whose length is not k.
How to talk through it
- 1Clarify. Digits 1 to 9 only, each at most once, and order inside a pick does not matter?
- 2Note the size. Only 512 subsets exist, so even checking all of them is fast.
- 3Build in order. Choose digits in increasing order so each set is made once.
- 4Prune. Break when even d repeated for every open slot overshoots what is left.
- 5Test out loud. Run n too small, n too large, k = 9 and a case with one answer.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?