All lessons

Backtracking

10 min · Python examples

Try choices, undo when they fail, and search all valid combinations.

PHP · Backtracking0/5 cleared

Enemy 1 of 5

This code builds every possible subset of the list by choosing to skip or include each number, then undoing the choice to try the other path. Press Run to see how many subsets it finds.

Why this works

Backtracking builds an answer piece by piece. Make a choice, recurse, then undo (backtrack) if the path doesn't work.

Generating all subsets is the hello-world of backtracking.

You
Cosmic-Ray Alien
Loading editor…
Target output: 8