Problem 216

Abstract / Summary

Find all valid combinations of numbers from 1 to 9 that add up to a given target with each number used at most once.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
16 lines | 493 bytes | submitted August 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 j already contains k-1 elements, adding the current number i would complete a candidate of size k. The algorithm checks whether the sum of j plus i equals the target n. If the equality holds, the completed combination is stored in result.
if len(j) == k - 1:
    if i + sum(j) == n:
        result.append(j + [i])
  • When j is shorter than k-1, the algorithm determines whether extending j with i could still lead to a valid solution. The condition i + sum(j) <= n guarantees 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 k is larger than 9, no combination can be formed because only nine distinct digits exist. The loop will never reach a state where len(j) == k-1, leaving result empty.
  • When n exceeds the maximum possible sum of the largest k numbers (for example, k = 3 and n = 30), the condition i + sum(j) <= n prevents any extension, resulting in an empty result.
  • If n is too small to be reached by the smallest k numbers (e.g., k = 4 and n = 3), the same pruning condition stops all growth early, again yielding an empty list.
  • The check len(j) == k - 1 ensures that only combinations of exactly k elements 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.48 | σ = 1.85

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
49 links | 32 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Combination Sum III | Leetcode 216 | Backtracking | Day-10'
Ayushi Sharma 18 mins
Combination Sum III | Leetcode 216 | Backtracking | Day-10
YouTube video 'Combination Sum III | Leet code 216 | Theory explained + Python code'
Sai Anish Malla 14 mins
Combination Sum III | Leet code 216 | Theory explained + Python code
YouTube video 'Backtracking Template : Combination Sum III | September Leetcode challenge Day 12 | Leetcode 216'
Coding Decoded 14 mins
Backtracking Template : Combination Sum III | September Leetcode challenge Day 12 | Leetcode 216
YouTube video 'Leetcode 216. Combination Sum III'
Fraz 5 mins
Leetcode 216. Combination Sum III
YouTube video 'Combination Sum III - LeetCode 216 - JavaScript'
AlgoJS 6 mins
Combination Sum III - LeetCode 216 - JavaScript
YouTube video 'Daily Leetcode #770: May 10, 2022 - 216. Combination Sum III'
Programming Live with Larry 12 mins
Daily Leetcode #770: May 10, 2022 - 216. Combination Sum III
YouTube video '216. Combination Sum III (Leetcode Medium)'
Programming Live with Larry 26 mins
216. Combination Sum III (Leetcode Medium)
YouTube video 'Combination Sum III | Leetcode 216 | Backtracking in Python | Explained in Telugu | srkcodes'
Srk Codes 9 mins
Combination Sum III | Leetcode 216 | Backtracking in Python | Explained in Telugu | srkcodes
YouTube video 'Unique K-Number Sum | Combination Sum III | Backtracking | Recurrsion'
Sanyam IIT Guwahati 12 mins
Unique K-Number Sum | Combination Sum III | Backtracking | Recurrsion
YouTube video 'Daily Leetcode #165: Sep 12, 2020 - 216. Combination Sum III'
Programming Live with Larry 9 mins
Daily Leetcode #165: Sep 12, 2020 - 216. Combination Sum III
YouTube video 'Leetcode 216 - Combination Sum III | Recursion & Backtracking JavaScript Solution'
Web Coder Abhishek 6 mins
Leetcode 216 - Combination Sum III | Recursion & Backtracking JavaScript Solution
YouTube video 'Day 72: LeetCode Problem 216. Combination Sum III - Swift'
iOSxBank 10 mins
Day 72: LeetCode Problem 216. Combination Sum III - Swift
YouTube video 'Combination Sum III | Leetcode 216 | Approach + Code with explanation.'
Pirai's Academy 19 mins
Combination Sum III | Leetcode 216 | Approach + Code with explanation.
YouTube video 'Amazon Coding Interview Question | Leetcode 216 | Combination Sum III'
WorkWithGoogler 7 mins
Amazon Coding Interview Question | Leetcode 216 | Combination Sum III
YouTube video 'LeetCode 216 | Combination Sum III | Recursion | Java'
Sleepy Cracker 6 mins
LeetCode 216 | Combination Sum III | Recursion | Java
YouTube video 'LeetCode 216. Combination Sum III'
Francesco Manicardi 5 mins
LeetCode 216. Combination Sum III
YouTube video 'Combination Sum III Explained - Backtracking LeetCode 216'
CodeLucky 5 mins
Combination Sum III Explained - Backtracking LeetCode 216
YouTube video 'Leetcode 216. Combination Sum III - backtracking'
Code-Yao 9 mins
Leetcode 216. Combination Sum III - backtracking
YouTube video 'Leetcode Question 216 "Combination Sum III" in Python'
Ghumman Tech 7 mins
Leetcode Question 216 "Combination Sum III" in Python
19 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

20 solutions   August 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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