Recursion & Backtracking · Pattern 3 of 9
Pick / not-pick: subsets, combinations and sums
For each item, either take it or skip it. That binary choice generates every subset; a start index, a target and a duplicate rule turn it into combinations, combination sums and bucket filling.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- All subsets, or all combinations of k items
- Choose items that add up to a target
- Split items into groups with equal sums
- Each item is either in or out of the answer
The template
// pick / not-pick: two branches per item
List<List<Integer>> subsets(int[] a) {
List<List<Integer>> out = new ArrayList<>();
pick(a, 0, new ArrayList<>(), out);
return out;
}
void pick(int[] a, int i, List<Integer> path, List<List<Integer>> out) {
if (i == a.length) { out.add(new ArrayList<>(path)); return; }
path.add(a[i]);
pick(a, i + 1, path, out); // take a[i]
path.remove(path.size() - 1);
pick(a, i + 1, path, out); // skip a[i]
}
// loop form with a start index: sort, then skip equal siblings (duplicates allowed in input)
List<List<Integer>> subsetsWithDup(int[] a) {
Arrays.sort(a);
List<List<Integer>> out = new ArrayList<>();
loop(a, 0, new ArrayList<>(), out);
return out;
}
void loop(int[] a, int start, List<Integer> path, List<List<Integer>> out) {
out.add(new ArrayList<>(path)); // every node is a subset
for (int i = start; i < a.length; i++) {
if (i > start && a[i] == a[i - 1]) continue; // same value, same level
path.add(a[i]);
loop(a, i + 1, path, out);
path.remove(path.size() - 1);
}
}
// combination sum: an item may be reused, so recurse with i, not i + 1
List<List<Integer>> combinationSum(int[] a, int target) {
Arrays.sort(a);
List<List<Integer>> out = new ArrayList<>();
sum(a, 0, target, new ArrayList<>(), out);
return out;
}
void sum(int[] a, int start, int left, List<Integer> path, List<List<Integer>> out) {
if (left == 0) { out.add(new ArrayList<>(path)); return; }
for (int i = start; i < a.length && a[i] <= left; i++) { // sorted: stop early
path.add(a[i]);
sum(a, i, left - a[i], path, out);
path.remove(path.size() - 1);
}
} def subsets(a): # pick / not-pick: two branches per item
out, path = [], []
def pick(i):
if i == len(a):
out.append(path[:])
return
path.append(a[i]); pick(i + 1) # take a[i]
path.pop(); pick(i + 1) # skip a[i]
pick(0)
return out
def subsets_with_dup(a): # loop form: sort, skip equal siblings
a, out, path = sorted(a), [], []
def loop(start):
out.append(path[:]) # every node is a subset
for i in range(start, len(a)):
if i > start and a[i] == a[i - 1]:
continue # same value, same level
path.append(a[i]); loop(i + 1); path.pop()
loop(0)
return out
def combination_sum(a, target): # reuse allowed: recurse with i, not i + 1
a, out, path = sorted(a), [], []
def go(start, left):
if left == 0:
out.append(path[:])
return
for i in range(start, len(a)):
if a[i] > left:
break # sorted: nothing later fits either
path.append(a[i]); go(i, left - a[i]); path.pop()
go(0, target)
return out // pick / not-pick: two branches per item
void pick(vector<int>& a, int i, vector<int>& path, vector<vector<int>>& out) {
if (i == (int)a.size()) { out.push_back(path); return; }
path.push_back(a[i]);
pick(a, i + 1, path, out); // take a[i]
path.pop_back();
pick(a, i + 1, path, out); // skip a[i]
}
vector<vector<int>> subsets(vector<int>& a) {
vector<vector<int>> out; vector<int> path;
pick(a, 0, path, out);
return out;
}
// loop form with a start index: sort, then skip equal siblings
void loop(vector<int>& a, int start, vector<int>& path, vector<vector<int>>& out) {
out.push_back(path); // every node is a subset
for (int i = start; i < (int)a.size(); i++) {
if (i > start && a[i] == a[i - 1]) continue; // same value, same level
path.push_back(a[i]);
loop(a, i + 1, path, out);
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& a) {
sort(a.begin(), a.end());
vector<vector<int>> out; vector<int> path;
loop(a, 0, path, out);
return out;
}
// combination sum: an item may be reused, so recurse with i, not i + 1
void sumGo(vector<int>& a, int start, int left, vector<int>& path, vector<vector<int>>& out) {
if (left == 0) { out.push_back(path); return; }
for (int i = start; i < (int)a.size() && a[i] <= left; i++) { // sorted: stop early
path.push_back(a[i]);
sumGo(a, i, left - a[i], path, out);
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& a, int target) {
sort(a.begin(), a.end());
vector<vector<int>> out; vector<int> path;
sumGo(a, 0, target, path, out);
return out;
} // pick / not-pick: two branches per item
function subsets(a) {
const out = [], path = [];
function pick(i) {
if (i === a.length) { out.push([...path]); return; }
path.push(a[i]); pick(i + 1); // take a[i]
path.pop(); pick(i + 1); // skip a[i]
}
pick(0);
return out;
}
// loop form with a start index: sort, then skip equal siblings
function subsetsWithDup(a) {
a = [...a].sort((x, y) => x - y);
const out = [], path = [];
function loop(start) {
out.push([...path]); // every node is a subset
for (let i = start; i < a.length; i++) {
if (i > start && a[i] === a[i - 1]) continue; // same value, same level
path.push(a[i]); loop(i + 1); path.pop();
}
}
loop(0);
return out;
}
// combination sum: an item may be reused, so recurse with i, not i + 1
function combinationSum(a, target) {
a = [...a].sort((x, y) => x - y);
const out = [], path = [];
function go(start, left) {
if (left === 0) { out.push([...path]); return; }
for (let i = start; i < a.length && a[i] <= left; i++) { // sorted: stop early
path.push(a[i]); go(i, left - a[i]); path.pop();
}
}
go(0, target);
return out;
} The variations
-
1Two choices with a rule
At each position you have two options, and a simple rule removes some of them: no
1right after a1, or no)unless an open(is waiting. Check the rule before you recurse.Now you solve -
2Take it or leave it
For item
i, recurse once with it and once without it. After the last item, the path is one subset. A take can be blocked, for example when a string shares letters with what you already took.Now you solve -
3Skip duplicates among siblings
Sort first. In the loop form, skip
a[i]when it equalsa[i − 1]andi > start: the same value was already tried at this level, so its subtree would repeat.Now you solve- Combination Sum II Medium Stuck? ▶ video
-
4Reach a target sum
Pass down how much is left. Stop when it hits zero, and break the loop as soon as a sorted item is too big. Reuse an item by recursing with
i; use it once withi + 1.Now you solve -
5Fill k buckets
Each item picks a bucket instead of in or out. The buckets must each reach
total / k. Sort big items first and never try two empty buckets for the same item: they are the same choice.Now you solve
Mistakes to avoid
- Skipping duplicates with
i > 0instead ofi > start: that also throws away valid answers like[1, 1]. - Recursing with
i + 1when items may be reused (or withiwhen they may not). - Bucket problems: not sorting the items in decreasing order, and not skipping empty buckets you already tried, which makes the search far too slow.
Lesson done
Next: Permutations: every order of the items →Mark it done once you can write the template from memory and you have solved the worked examples yourself.