LeetCode 39. Combination Sum
🧩 Problem Description
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 choose the same number from candidates
an unlimited number of times.
Two combinations are unique if the frequency of at least one number is different.
Return the combinations in any order.
💬 Example
1 | Input: candidates = [2,3,6,7], target = 7 |
1 | Input: candidates = [2,3,5], target = 8 |
💡 Approach: Backtracking with Start Index
- Sort
candidates
(optional, helps early pruning). - Use DFS to build combinations:
- Maintain
start
index to avoid permutations of the same combination. - At each step, you can reuse the same index (unlimited usage).
- If
sum == target
, push the current path. - If
sum > target
, backtrack (prune).
- Maintain
🔢 Java Code
1 | import java.util.*; |
⏱ Complexity Analysis
Let N = len(candidates)
, T = target
, and assuming reasonable pruning:
- Time: ~O(number of valid combos) in practice; upper bound often expressed as O(N^(T/minVal)) in worst cases.
- Space: O(T/minVal) recursion depth + output size.
✍️ Summary
- Classic unbounded knapsack (combinations) via backtracking.
- Use a start index to avoid duplicate permutations.
- Prune when the partial sum exceeds
target
.
Related problems:
lc-40
— Combination Sum II (each number used at most once, with duplicates)lc-216
— Combination Sum IIIlc-377
— Combination Sum IV (order matters, DP)