Backtracking tutorial

Choose, explore, un-chooseWorld 4 tutorial
0:00 / 0:00

Build an answer one choice at a time and undo the ones that lead nowhere: choose, recurse, then un-choose so the next choice starts clean.

▼

Transcript

Backtracking: build an answer one choice at a time, and undo choices that lead nowhere.

In a cave of forks, the explorer picks a tunnel and goes deeper, dropping breadcrumbs. Dead end? Step back, pick up the crumb, try the next. Complete paths get recorded.

In code, three beats. Choose: add a number. Explore: recurse. Un-choose: pop it, so the next choice starts clean.

The clue: all, every, or generate, with combinations, permutations or subsets, and a small N.

The cost is exponential: it visits every candidate, like two to the N subsets, so keep inputs small. Now let's use it on Subsets.