BeginnerCoder

Lesson 21 — Backtracking: subsets

Backtracking: choose, explore, undo

Backtracking explores every possibility by making a choice, exploring everything that follows, then undoing the choice to try the next one. For subsets: add a number to the current path, recurse, then pop it off.

picked.append(item)   # choose
search(...)           # explore
picked.pop()          # undo

We save a copy of the path (path[:]) because the list keeps changing afterwards.

Why it matters: Sudoku solvers, permutations, timetables and puzzle games are all backtracking.

Want it another way?
Task

Fill in choose / explore / undo inside the loop. Expected: all 8 subsets of [1, 2, 3].

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Algorithms Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.