In the Combination Sum III interview question, you must find all combinations of k numbers that sum up to a target n, using only numbers from 1 to 9. Each number can be used at most once. This problem is more constrained than the others, as it limits both the available pool of numbers and the size of the combination.
Companies like Microsoft and Amazon ask this Backtracking interview pattern to see if you can handle multiple constraints simultaneously (sum constraint and count constraint). It's also a good test of efficiency, as the search space is quite small (subsets of {1..9}), allowing candidates to focus on clean code and early pruning.
The core pattern is Backtracking with two stopping conditions:
k numbers.n.
Because the numbers are strictly increasing (1 to 9), the search is naturally ordered, making it easier to avoid duplicate combinations.k = 3, n = 7
1:
2:
3: Sum is 1+2+3 = 6. (Too small, only 3 numbers allowed).4: Sum is 1+2+4 = 7. (Success! Add [1, 2, 4]).5: Sum 1+2+5 = 8. (Too big, Stop).2:
3: Sum is 2+3+?. Next number must be 2. But we can't reuse numbers.
No other combinations will work for k=3 and n=7.Since the pool is limited to 1-9, the total number of combinations is very small (2^9 = 512). This is a great problem to practice the "Bitmask" approach as an alternative to backtracking.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Construct the Lexicographically Largest Valid Sequence | Medium | Solve | |
| Combination Sum II | Medium | Solve | |
| Permutations | Medium | Solve | |
| Combination Sum | Medium | Solve | |
| Permutations III | Medium | Solve |