Leetcode #216: Combination Sum III
In this guide, we solve Leetcode #216 Combination Sum III in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Backtracking
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.
Python Solution
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def dfs(i: int, s: int):
if s == 0:
if len(t) == k:
ans.append(t[:])
return
if i > 9 or i > s or len(t) >= k:
return
t.append(i)
dfs(i + 1, s - i)
t.pop()
dfs(i + 1, s)
ans = []
t = []
dfs(1, n)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.