Combination Sum III
Problem
Given two integers k and n, return all possible combinations of k numbers that add up to n, where only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
- 2 ≤ k ≤ 9
- 1 ≤ n ≤ 60
Example
k = 3, n = 7[[1,2,4]]The brute-force approach would try all combinations of numbers from 1 to 9 of length k and check if their sum equals n, which is inefficient. The backtracking approach incrementally builds combinations, pruning paths early when the sum exceeds n or the combination length reaches k. For example, starting from 1, the algorithm tries adding 2 and 4 to reach the sum 7 with length 3, which is a valid combination and added to the result. It then backtracks to explore other possibilities, but prunes any path where the sum exceeds 7 or the length exceeds 3.
Approach
Straightforward Solution
A brute-force approach would generate all subsets of numbers 1 to 9 and filter those with length k and sum n. This approach is O(2^9) = O(512) in the worst case, which is feasible but inefficient and does not prune early.
Core Observation
The problem requires enumerating all unique combinations of k distinct numbers from 1 to 9 that sum to n. This is a classic combinatorial search problem with constraints on combination length and sum.
Path to Optimal
The key insight is to use backtracking to build combinations incrementally, pruning any path where the sum exceeds n or the length exceeds k. By starting from the smallest number and moving upwards, the algorithm avoids duplicates and ensures combinations are unique and sorted. Early pruning drastically reduces the search space compared to brute force.
Optimal Approach
Use a recursive backtracking function that tries numbers from the current start to 9, adding each to the current path if it does not exceed the target sum. When the path length reaches k, check if the sum equals n and add a copy of the path to the result if so. Backtrack by removing the last number and continue exploring. This approach guarantees all valid combinations are found efficiently.
Time
O(C(9, k))
The algorithm explores combinations of size k from 9 numbers, which is bounded by the binomial coefficient C(9, k). Early pruning reduces unnecessary exploration, making the practical runtime efficient.
Space
O(k)
The recursion stack and path list grow up to size k, which is the maximum combination length, representing the auxiliary space used during backtracking.
Pattern Spotlight
Backtracking (State Restoration)
For combination problems with constraints, use backtracking with incremental construction and early pruning, always restoring state after exploring each choice to enable exhaustive yet efficient search.
Solution
| 1 | class Solution: |
| 2 | def combinationSum3(self, k: int, n: int) -> List[List[int]]: |
| 3 | result = [] |
| 4 | |
| 5 | def backtrack(start, path, total): |
| 6 | if len(path) == k: |
| 7 | if total == n: |
| 8 | result.append(path.copy()) |
| 9 | return |
| 10 | |
| 11 | for num in range(start, 10): |
| 12 | if total + num > n: |
| 13 | break |
| 14 | |
| 15 | path.append(num) |
| 16 | backtrack(num + 1, path, total + num) |
| 17 | path.pop() |
| 18 | |
| 19 | backtrack(1, [], 0) |
| 20 | return result |
Step-by-Step Solution
Initialize Result Container to Collect Valid Combinations
| 3 | result = [] |
Objective
To prepare a list that will store all valid combinations found during the backtracking process.
Key Insight
Having a dedicated result list allows the algorithm to accumulate valid solutions incrementally. This separation of concerns keeps the recursive function focused on exploration and validation, while the result list collects final answers.
Interview Quick-Check
Core Logic
The result list stores all valid combinations found by the backtracking function.
State & Boundaries
The result list is initialized once before recursion begins and returned after all exploration completes.
Explore Combinations Recursively with Early Pruning
| 5 | def backtrack(start, path, total): |
| 6 | if len(path) == k: |
| 7 | if total == n: |
| 8 | result.append(path.copy()) |
| 9 | return |
| 11 | for num in range(start, 10): |
| 12 | if total + num > n: |
| 13 | break |
| 15 | path.append(num) |
| 16 | backtrack(num + 1, path, total + num) |
| 17 | path.pop() |
Objective
To recursively build combinations by adding numbers from the current start to 9, pruning paths that exceed the target sum or combination length.
Key Insight
The backtracking function incrementally constructs candidate combinations, checking two critical conditions: if the combination length equals k, it verifies if the sum matches n and adds the combination to the result if valid; if the sum exceeds n, it prunes the path immediately to avoid unnecessary exploration. By iterating from the current start number upwards, the algorithm avoids duplicates and ensures combinations are sorted.
Interview Quick-Check
Core Logic
Backtracking uses incremental construction with pruning: it stops exploring paths where the sum exceeds n or the combination length reaches k without matching n.
State & Boundaries
The recursion advances the start number to avoid reusing numbers and to maintain ascending order in combinations.
Common Pitfalls & Bugs
Failing to backtrack by removing the last added number after recursion leads to incorrect state and duplicate or invalid combinations.
Complexity
Early pruning reduces the search space from all subsets to only those that can potentially sum to n with length k, improving efficiency.
Initiate Backtracking and Return All Valid Combinations
| 19 | backtrack(1, [], 0) |
| 20 | return result |
Objective
To start the recursive exploration from number 1 with an empty path and zero sum, and return the collected results after completion.
Key Insight
Starting from 1 ensures all combinations use numbers from 1 to 9 in ascending order, preventing duplicates. Returning the result after recursion completes provides the final answer to the problem.
Interview Quick-Check
Core Logic
The initial call sets the starting point for exploration and the base state for the path and sum.
State & Boundaries
Returning the result after recursion ensures all valid combinations have been collected.
Line Analysis
This solution has 3 Critical lines interviewers watch for.
path.pop()
Remove the last number from the path to backtrack.
This 'un-choose' step restores the path state, enabling exploration of alternative combinations without interference from previous choices.
result.append(path.copy())
Add a copy of the current path to the result list.
Copying the path is essential because the path list is mutable and will be modified during backtracking; storing a copy preserves the valid combination.
backtrack(num + 1, path, total + num)
Recursively call backtrack with updated start, path, and sum.
This recursive call explores deeper combinations, advancing the start to avoid duplicates and updating the sum to reflect the new path.
if total == n:
Check if the current sum equals the target n.
Only combinations of length k with sum exactly n are valid solutions, so this check filters out invalid candidates.
if total + num > n:
Prune the search if adding the current number exceeds the target sum.
Early pruning prevents unnecessary exploration of paths that cannot yield valid combinations, improving efficiency.
if len(path) == k:
Check if the current path length equals k.
This condition identifies when a candidate combination has reached the required length, triggering validation of the sum.
return
Return from the function to stop exploring this path further.
Once a valid combination is found or the path length reaches k, no further exploration is needed along this branch.
break
Break the loop to stop exploring further numbers once the sum limit is exceeded.
Since numbers are increasing, any further numbers will only increase the sum, so breaking avoids futile exploration.
path.append(num)
Add the current number to the path.
This 'choose' step extends the current combination candidate with a new number for further exploration.
def backtrack(start, path, total):
Define the recursive backtracking function with parameters for start number, current path, and current sum.
Encapsulating the recursive logic in a helper function allows clean management of state and parameters during exploration.
for num in range(start, 10):
Iterate over numbers from the current start to 9.
This loop explores all possible next numbers to add to the combination, maintaining ascending order and uniqueness.
backtrack(1, [], 0)
Start backtracking from number 1 with an empty path and zero sum.
This initial call sets the exploration starting point, ensuring all combinations use numbers from 1 to 9 in ascending order.
return result
Return the list of all valid combinations found.
After exhaustive exploration, this returns the final answer to the caller.
result = []
Initialize an empty list to store valid combinations.
This list accumulates all valid combinations found during backtracking, separating result collection from exploration logic.
Test Your Understanding
Why is it necessary to backtrack (remove the last number) after each recursive call in this algorithm?
Backtracking restores the state of the current path so that the algorithm can explore alternative combinations without carrying over previous choices, ensuring all unique combinations are explored correctly.
Related Problems
Backtracking pattern
Don't just read it. Drill it.
Reconstruct Combination Sum III from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Combination Sum III drill