TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN
Backtracking: Decision Trees With Push / Recurse / Pop
Systematically enumerate every valid subset, permutation, or configuration by mutating and unwinding one shared path.
backtrackingdfsrecursioncombinatorics
The core idea
When asked to materialize ALL valid configurations for small N (N ≤ 20), branch on each choice—push onto path, recurse, and pop to restore the parent state cleanly.
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING BACKTRACKING TREE SIM...
What to say out loud
Canonical Python template
def subsets(items: list[str]) -> list[list[str]]:
res, path = [], []
def dfs(i: int) -> None:
if i == len(items):
res.append(path.copy())
return
path.append(items[i]); dfs(i + 1)
path.pop(); dfs(i + 1)
dfs(0)
return res