Python 0216.py
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
current = [ [ ] ]
for i in range(9, 0, -1):
next = []
for j in current:
if len(j) == k - 1:
if i + sum(j) == n:
result.append(j + [i])
elif i + sum(j) <= n:
next.append(j + [i])
current = current + next
return result
Difficulty
and has an acceptance rate of about 74% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “Combination Sum III” problem: find all unique sets of k distinct numbers from 1 to 9 that add up to n. The algorithm builds candidate combinations in a reverse numeric order, progressively extending partial solutions while pruning impossible branches early. The final result is a list of lists, each inner list representing a valid combination in ascending order.
Initialization
The method begins by preparing two containers: result to store completed combinations and current to hold partial combinations that are still under construction. current is seeded with an empty list, representing the starting point for building any combination.
result = []
current = [[]]
Iteration over candidates
A descending loop iterates over the numbers 9 down to 1. The reverse order ensures that when a number is appended to a partial combination, the resulting list remains in descending order, which later translates to ascending order after the final reversal of each combination.
for i in range(9, 0, -1):
Building combinations
Inside the outer loop, a temporary list next collects new partial combinations that can still be extended. The inner loop examines each partial combination j currently available.
next = []
for j in current:
Two distinct paths are taken based on the length of j:
- When
jalready containsk-1elements, adding the current numberiwould complete a candidate of sizek. The algorithm checks whether the sum ofjplusiequals the targetn. If the equality holds, the completed combination is stored inresult.
if len(j) == k - 1:
if i + sum(j) == n:
result.append(j + [i])
- When
jis shorter thank-1, the algorithm determines whether extendingjwithicould still lead to a valid solution. The conditioni + sum(j) <= nguarantees that the partial sum does not exceed the target, allowing the new partial combination to be kept for further expansion.
elif i + sum(j) <= n:
next.append(j + [i])
After processing all partial combinations for the current i, the current list is updated to include both the existing partial combinations and the newly generated ones stored in next. This cumulative approach preserves all viable paths for subsequent iterations.
current = current + next
Result accumulation
When the outer loop finishes, result contains every combination that satisfies both the size constraint (k numbers) and the sum constraint (n). Each combination is built in descending order because numbers are appended from high to low. The final return statement delivers the collected solutions directly.
return result
Edge case handling
The algorithm implicitly handles several edge conditions:
- If
kis larger than 9, no combination can be formed because only nine distinct digits exist. The loop will never reach a state wherelen(j) == k-1, leavingresultempty. - When
nexceeds the maximum possible sum of the largestknumbers (for example,k = 3andn = 30), the conditioni + sum(j) <= nprevents any extension, resulting in an emptyresult. - If
nis too small to be reached by the smallestknumbers (e.g.,k = 4andn = 3), the same pruning condition stops all growth early, again yielding an empty list. - The check
len(j) == k - 1ensures that only combinations of exactlykelements are considered for final validation, preventing premature inclusion of shorter lists.
Performance considerations
The code employs a forward-building strategy that avoids generating the full power set of numbers 1 to 9. By pruning any partial combination whose sum already exceeds n, the algorithm discards large swaths of the search space early, reducing the number of recursive-like expansions. The use of a simple list concatenation (current = current + next) keeps the data structure flat, avoiding the overhead of deeper recursion or explicit stack management. Additionally, the descending iteration order guarantees that each number is considered only once per combination, eliminating duplicate permutations without needing an explicit visited set. These choices collectively keep the execution efficient for the constrained domain of nine digits.
ELI5 - Simplified Explanation
Imagine you have a big box of number tiles labeled one through nine. The goal is to pick exactly a certain amount of these tiles so that they add up to a secret target number. Since you want to find every possible way to do this, the computer starts with an empty list where it keeps track of the combinations being built.
The computer walks backward through the numbers from nine down to one. For every number it looks at, it checks all the groups it has already started creating. If a group is almost finished and adding the current number makes the total reach the secret goal, then that set is saved as a perfect match. If a group still has space for more numbers and the total is not too big yet, the computer adds the current number to that group so it can keep growing. This process happens over and over until every possible combination has been explored to see if it works.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Rust | JS | Java | C# | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 39: Combination Sum
Solved On The Same Day
- problem 455: Assign Cookies
- problem 500: Keyboard Row
- problem 575: Distribute Candies
- problem 1009: Complement of Base 10 Integer
- problem 1071: Greatest Common Divisor of Strings
- problem 1299: Replace Elements with Greatest Element on Right Side
- problem 1748: Sum of Unique Elements
- problem 1979: Find Greatest Common Divisor of Array
- problem 2148: Count Elements With Strictly Smaller and Greater Elements
- problem 2309: Greatest English Letter in Upper and Lower Case
- problem 229: Majority Element II
- problem 373: Find K Pairs with Smallest Sums
- problem 470: Implement Rand10() Using Rand7()
- problem 503: Next Greater Element II
- problem 556: Next Greater Element III
- problem 622: Design Circular Queue
- problem 1262: Greatest Sum Divisible by Three
- problem 2657: Find the Prefix Common Array of Two Arrays
- problem 2807: Insert Greatest Common Divisors in Linked List
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality