Combination Sum
Pattern: Combination sum
At each candidate, either use it (and stay on it, since it may be used again) or move past it for good. Moving only forward makes every combination appear once.
The problem
Given an array of different positive whole numbers and a target, return every combination of them that adds up to the
target. A number may be used any number of times. Two combinations are the same if they use the same numbers the same
number of times. For example, [2, 3, 6, 7] with target 7 gives [2, 2, 3] and [7].
The function name combinationSum matches LeetCode. Use the link above for the exact statement and limits. Any order is
accepted, so the tests sort before comparing.
Think first
- How do you allow a number to be used again?
- How do you stop
[2, 3, 2]and[2, 2, 3]both appearing? - When does a branch end?
Hints
Brute force, and why it fails
Try every multiset of candidates up to the target and keep the ones with the right sum: hard to bound and wasteful. Backtracking with the two branches explores only sums that do not overshoot.
The key insight
A combination is a count of how many times each candidate is used. Deciding those counts candidate by candidate, in a fixed order, lists each combination exactly once.
Dry run
| left | 7 |
|---|---|
| cur | [] |
candidates = [2, 3, 6, 7] and target = 7.
The plan
function build(i, left, cur):
if left == 0: record a copy of cur; return
if i == n or left < 0: return
add c[i]; build(i, left - c[i], cur); remove it
build(i + 1, left, cur)
build(0, target, [])
Complexity
- Time
O(n^(target / min))- Space
O(target / min)
The depth is at most target / smallest candidate, and each level branches at most twice per candidate. The output can
be large.
Edge cases
- No combination, as in
[2]with target 1: empty. - Using one candidate many times, as in
[1]with target 2:[1, 1]. - A candidate equal to the target: a combination of one.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> out = new ArrayList<>();
build(candidates, 0, target, new ArrayList<>(), out);
return out;
}
private void build(int[] c, int i, int left, List<Integer> cur, List<List<Integer>> out) {
if (left == 0) { out.add(new ArrayList<>(cur)); return; }
if (i == c.length || left < 0) return;
cur.add(c[i]); // use c[i] (again): stay on i
build(c, i, left - c[i], cur, out);
cur.remove(cur.size() - 1);
build(c, i + 1, left, cur, out); // or move past c[i] for good
}
}C++
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> out;
vector<int> cur;
build(candidates, 0, target, cur, out);
return out;
}
void build(vector<int>& c, size_t i, int left, vector<int>& cur, vector<vector<int>>& out) {
if (left == 0) { out.push_back(cur); return; }
if (i == c.size() || left < 0) return;
cur.push_back(c[i]); // use c[i] (again): stay on i
build(c, i, left - c[i], cur, out);
cur.pop_back();
build(c, i + 1, left, cur, out); // or move past c[i] for good
}
};Python
class Solution:
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
out = []
def build(i: int, left: int, cur: list) -> None:
if left == 0:
out.append(cur[:])
return
if i == len(candidates) or left < 0:
return
cur.append(candidates[i]) # use candidates[i] (again): stay on i
build(i, left - candidates[i], cur)
cur.pop()
build(i + 1, left, cur) # or move past it for good
build(0, target, [])
return outCommon mistakes
- Recursing on
i + 1after using a candidate, which forbids reuse. - Restarting from index 0 in every call, which lists every order of the same combination.
- Forgetting to copy the list when recording.