All topics
59

Every on-off combination of a list

Tier 1Locked

Where it runs

1. The problem

In the last lessons recursion computed one answer: the size of a folder, a Fibonacci number. Backtracking uses the same self-calls to walk every path and collect an answer on each one. At each step it tries a choice, goes deeper, then undoes that choice and tries the next one. There is one new idea here: that undo, putting everything back the way it was before the next try.

You are shipping a release with three feature flags (switches that turn features of a program on or off). Before it goes out, CI (a system that checks code automatically) has to test the release under every combination of the flags. All off, only the first on, the first and third on, all on, and so on. You need the full list of on-off combinations.

For three flags there are 8 combinations. For ten flags there are 1024. Writing them out by hand is not realistic. Nested loops don't work either: the number of flags changes, and every count would need its own depth of nesting.

You need a function that walks the list and, at every item, tries both answers: leave the item out or put it in. Every path from start to end gives one combination.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included
Building every sequence by choose, explore, undo
backtrack([], [1, 2], [])
choices
1
2
path (choices made so far)
empty
result
empty
path.length = 0

List every sequence of length 2 built from [1, 2]. The loop offers every choice at every level, so a value can repeat.

Recognise it

Backtracking

Say these words and it is this pattern

  • generate all subsets/permutations/combinations
  • n is small (roughly n <= 12-20), exponential search is acceptable
  • make a choice, recurse, then undo it before trying the next choice
  • place items under constraints and back off on conflict (N-Queens, Sudoku)
  • return every valid arrangement, not just one

Looks similar, isn't

The output is exponential, so n stays small. Subsets of 20 items are 1e6, permutations of 10 are 3.6e6.

On LeetCode

Problems that list every subset or every combination of choices, one choice per item. Branch on each item, recurse, then undo the choice before the next branch.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy