Module 6 · Recursion, Backtracking and Divide and Conquer · Lesson 21 of 40

Backtracking: try, then undo

Explore every choice like paths in a maze: choose, explore, undo. Build subsets, permutations and combinations.

In this lesson · about 25 minutes

  • Describe backtracking as a tree of choices
  • Use the choose → explore → undo pattern
  • Generate subsets and permutations

Think of a maze. At each fork, you pick a path. If it leads to a dead end, you walk back to the last fork and try another path. That is backtracking.

In code, backtracking is recursion with three steps at every choice:

  1. Choose: add an option to your current path.
  2. Explore: recurse to make the next choice.
  3. Undo: remove the option again, so you can try the next one.

The "undo" is the key. We share one path list across all calls, so we must clean up after ourselves.

def backtrack(path, choices):
    if done(path):
        results.append(path[:])   # save a COPY
        return
    for c in choices:
        path.append(c)            # choose
        backtrack(path, ...)      # explore
        path.pop()                # undo

Try it · see it work

Backtracking: build every subset

For each item, we either take it or skip it. Watch the path grow and shrink.

Items:

current path

[]

Deciding item 0 of 3

subsets found (0)

none yet

Step 1 of 24For each item we make one choice: take it or skip it. 3 items → 2^3 = 8 subsets.

Three classic shapes

ProblemQuestionHow many answers for n items
SubsetsWhich items do I take?2ⁿ
PermutationsIn what order?n! (n × (n−1) × … × 1)
CombinationsWhich k items, order doesn't matter?"n choose k"

These numbers grow very fast, so backtracking is often slow. We make it faster with pruning: if the path can't possibly lead to an answer (for example, the total is already too big), stop exploring that branch early.

Famous backtracking puzzles: Sudoku, N-Queens (place queens so none attack each other), word search in a letter grid, and finding numbers that add up to a target.

Try it: all orders of three letters

Exercise

All subsets

Finish subsets(items). For each index, first take the item (append, explore, pop), then skip it (explore without it). Save a copy of the path when every item has been decided.

Exercise

Coins that make a total

Write ways(coins, target) that returns every list of coins (each coin used at most once, kept in the given order) whose sum is exactly target. Prune: stop a branch as soon as its total goes over the target. All coins are positive.

Check your understanding0 of 4 correct

Question 1

1.What are the three steps at each choice in backtracking?

Question 2

2.Why save path[:] instead of path?

Question 3

3.How many subsets do 5 items have?

Question 4

4.What is pruning?

Quiz score: 0 of 4

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.