Combination Sum
LeetCode 39 · Medium · solution, intuition & step-by-step walkthrough
Recurse with the same index to allow reuse.
This is how I solved Combination Sum (LeetCode 39), 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
Each candidate can be reused, so after choosing candidates[i] you recurse starting from i again (not i+1). Stop when the running total hits or passes the target.
Approach
- 1
dfs(start, ds, total): over target → stop; equal → record.
- 2
For i from start: append, dfs(i, …), pop.
How I solved it
Backtracking with reusePythonexponential
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res=[]
def dfs(start,ds,total):
if total>target:
return
if total==target:
res.append(ds[:])
return
for i in range(start,len(candidates)):
ds.append(candidates[i])
dfs(i,ds,total+candidates[i]) #take duplicate
ds.pop()
dfs(0,[],0)
return resCombination Sum — FAQ
What is the intuition behind Combination Sum?
Each candidate can be reused, so after choosing candidates[i] you recurse starting from i again (not i+1). Stop when the running total hits or passes the target.
How do you solve Combination Sum (LeetCode 39)?
1. dfs(start, ds, total): over target → stop; equal → record. 2. For i from start: append, dfs(i, …), pop.
What is the time and space complexity of Combination Sum?
Time: O(2^(T/min)). Space: O(T/min). (Accepted approach: Backtracking with reuse.)
What are common mistakes in Combination Sum?
Starting the loop at start (not 0) prevents permutations of the same combination.