Combination Sum III
LeetCode 216 · Medium · solution, intuition & step-by-step walkthrough
Backtrack over 1..9 with count and sum checks.
This is how I solved Combination Sum III (LeetCode 216), a medium problem from the Combinations pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Choose k distinct digits from 1–9 that add up to n. Backtrack over increasing digits, recording when both the count and the sum match and stopping when the sum overshoots.
Approach
- 1
Candidates 1..9.
- 2
Record when total == n and length == k.
- 3
Stop when total > n.
- 4
Recurse with i+1 so each digit is used once.
How I solved it
BacktrackingPythonO(C(9,k)) time
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res=[]
candidates=[i+1 for i in range(9)]
def dfs(start,ds,total):
if total==n and len(ds)==k:
res.append(ds[:])
return
if total>n:
return
for i in range(start,len(candidates)):
if i!=start and candidates[i]==candidates[i-1]:
continue
ds.append(candidates[i])
dfs(i+1,ds,total+candidates[i])
ds.pop()
dfs(0,[],0)
return resCombination Sum III — FAQ
What is the intuition behind Combination Sum III?
Choose k distinct digits from 1–9 that add up to n. Backtrack over increasing digits, recording when both the count and the sum match and stopping when the sum overshoots.
How do you solve Combination Sum III (LeetCode 216)?
1. Candidates 1..9. 2. Record when total == n and length == k. 3. Stop when total > n. 4. Recurse with i+1 so each digit is used once.
What is the time and space complexity of Combination Sum III?
Time: O(C(9, k)). Space: O(k). (Accepted approach: Backtracking.)
What are common mistakes in Combination Sum III?
The duplicate check is harmless here — digits are already unique.