Learn / Recursion and backtracking

Subsets

Every element is either in a subset or not, so n elements give 2ⁿ subsets. The take-or-skip recursion walks those two choices for each element in turn. Sorting first and skipping equal values at the same depth removes repeated subsets when the input has duplicates.

How to recognise it

  • The question asks for all subsets, all subsequences, or the best subset under some rule.
  • n is small (about 20 or less), so 2ⁿ is affordable.
  • Each element has a yes/no choice that does not depend on order.

The idea in one picture

Walk along the elements holding an empty bag. At each element you decide: drop it in the bag, or walk past it. After the last element, whatever is in the bag is one subset. Every sequence of decisions gives a different subset.

Template: take or skip

function build(i, bag):
    if i == n: record a copy of bag; return
    add a[i] to bag; build(i + 1, bag); remove it     # take
    build(i + 1, bag)                                 # skip

With duplicates: one tree node per distinct subset

sort a
function build(start, bag):
    record a copy of bag
    for i from start to n - 1:
        if i > start and a[i] == a[i - 1]: continue
        add a[i]; build(i + 1, bag); remove it

Beyond listing them

ProblemWhat the subsets are used for
Subset Sums (SPOJ)count subsets with a sum in a range, by meet in the middle
Tug of Warthe best half-size subset, closest to half the total
Partition into K equal subsetsfill K buckets, backtracking on where each value goes

Common mistakes

  • Recording the bag itself instead of a copy, so every recorded subset changes later.
  • Skipping duplicates by value at every depth, which loses subsets like [2, 2].
  • Trying brute force 2ⁿ when n is 34; split the input in halves first.

Problems

0 of 6 solved

Check yourself

How many subsets does a set of 10 different numbers have?

In Subsets II, after sorting, why skip a[i] when a[i] == a[i - 1] and i > start?

Meet in the middle for subset sums splits the array into two halves. Why does that help?