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.

5 variations · 11 problems · 8 with animated walkthroughs

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
// 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);
    }
}

The variations

  1. 1Two choices with a rule

    At each position you have two options, and a simple rule removes some of them: no 1 right after a 1, or no ) unless an open ( is waiting. Check the rule before you recurse.

  2. 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.

  3. 3Skip duplicates among siblings

    Sort first. In the loop form, skip a[i] when it equals a[i − 1] and i > start: the same value was already tried at this level, so its subtree would repeat.

    Now you solve
  4. 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 with i + 1.

    Now you solve
  5. 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 > 0 instead of i > start: that also throws away valid answers like [1, 1].
  • Recursing with i + 1 when items may be reused (or with i when 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.
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.