Leetcode #39: Combination Sum
In this guide, we solve Leetcode #39 Combination Sum 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
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
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: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Python Solution
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(i: int, s: int):
if s == 0:
ans.append(t[:])
return
if s < candidates[i]:
return
for j in range(i, len(candidates)):
t.append(candidates[j])
dfs(j, s - candidates[j])
t.pop()
candidates.sort()
t = []
ans = []
dfs(0, target)
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.