Combination Sum
The problem
Section titled “The problem”You get an array of distinct positive integers and a target. Return every unique combination of those numbers that sums to the target. You may use the same number any number of times. Two combinations are the same if they use the same counts of each number.
candidates = [2, 3, 6, 7], target = 7 -> [[2, 2, 3], [7]]Key insight
Section titled “Key insight”Think of a tree where each step picks a number and subtracts it from the target. A branch ends when the remaining value hits 0 (record it) or goes negative (dead end).
Two details make it correct:
- Reuse: recurse with
i, noti + 1, so the same number can be picked again. - No duplicates: the loop starts at
start, never earlier. So you can pick2then3, but never3then2. Each combination is built in one fixed order.
Sorting the candidates adds a cheap prune: once candidates[i] > remaining, every later
number is bigger too, so break out of the loop.
Show solutionHide solution
def combination_sum(candidates: list[int], target: int) -> list[list[int]]: candidates = sorted(candidates) # sorted lets us stop early res, path = [], []
def backtrack(start: int, remaining: int) -> None: if remaining == 0: res.append(path[:]) return for i in range(start, len(candidates)): if candidates[i] > remaining: break # prune: this and every later number is too big path.append(candidates[i]) # choose backtrack(i, remaining - candidates[i]) # explore: i, not i + 1, allows reuse path.pop() # un-choose
backtrack(0, target) return resexport function combinationSum(candidates: number[], target: number): number[][] { const nums = [...candidates].sort((a, b) => a - b); // sorted lets us stop early const res: number[][] = []; const path: number[] = [];
function backtrack(start: number, remaining: number): void { if (remaining === 0) { res.push([...path]); return; } for (let i = start; i < nums.length; i++) { if (nums[i] > remaining) break; // prune: this and every later number is too big path.push(nums[i]); // choose backtrack(i, remaining - nums[i]); // explore: i, not i + 1, allows reuse path.pop(); // un-choose } }
backtrack(0, target); return res;}import java.util.ArrayList;import java.util.Arrays;import java.util.List;
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { int[] nums = candidates.clone(); Arrays.sort(nums); // sorted lets us stop early List<List<Integer>> res = new ArrayList<>(); backtrack(nums, 0, target, new ArrayList<>(), res); return res; }
private void backtrack(int[] nums, int start, int remaining, List<Integer> path, List<List<Integer>> res) { if (remaining == 0) { res.add(new ArrayList<>(path)); return; } for (int i = start; i < nums.length; i++) { if (nums[i] > remaining) break; // prune: this and every later number is too big path.add(nums[i]); // choose backtrack(nums, i, remaining - nums[i], path, res); // explore: i, not i + 1, allows reuse path.remove(path.size() - 1); // un-choose } }}Complexity
Section titled “Complexity”- Time: O(N^(T/M)) — N candidates, target T, smallest candidate M. The tree is at most T/M deep with up to N branches per level. This is a loose upper bound; pruning and the start index make real runs much smaller. Copying each answer adds a factor of up to T/M.
- Space: O(T/M) — recursion depth and
pathhold at most T/M numbers (all the smallest candidate). The output is not counted.
Watch out for
Section titled “Watch out for”i, noti + 1, for the recursive call. Usingi + 1solves a different problem (each number used once).- Don’t restart the loop at 0. That generates
[2, 3, 2],[3, 2, 2]and[2, 2, 3]as three separate answers. - Subtract as you go. Passing
remainingis cheaper and clearer than re-summing the path.
Variations
Section titled “Variations”Combination Sum II (LeetCode 40)
Section titled “Combination Sum II (LeetCode 40)”Candidates may repeat, and each can be used once. Answers must be unique. The trick:
sort, recurse with i + 1, and skip a value when i > start and it equals the previous
one. That removes duplicate combinations at the same level.
Combination Sum III (LeetCode 216)
Section titled “Combination Sum III (LeetCode 216)”Choose exactly k distinct numbers from 1 to 9 that sum to n. The trick: same
template with i + 1, recording only when the path has k numbers and the sum is n.
Stop early when the path is already too long.
Coin Change II (LeetCode 518)
Section titled “Coin Change II (LeetCode 518)”Count (not list) the ways to make an amount from coins with unlimited reuse. The trick: backtracking is too slow. The same “loop coins outermost, allow reuse” order becomes a 1-D DP over amounts, which is also why combinations don’t count orderings twice.