Choose. Explore. Undo..
Enumerate candidates while restoring state between branches.
01 Model the idea
Backtracking explores a decision tree. Make one choice, recurse on the remaining problem, then undo that choice before exploring a sibling branch. Pruning stops branches that already violate constraints. The technique is powerful but can still require exponential or factorial work; a search tree’s size does not vanish because the code is short.
The current path contains exactly the choices made on the active branch.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
CHOOSE one unused option
EXPLORE the smaller remaining problem
UNDO the choice
RECORD only complete candidates03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def permutations(values):
result, path, used = [], [], set()
def visit():
if len(path) == len(values):
result.append(tuple(path)); return
for index, value in enumerate(values):
if index not in used:
used.add(index); path.append(value)
visit()
path.pop(); used.remove(index)
visit()
return result
print(permutations(["A", "B"]))[('A', 'B'), ('B', 'A')]- 1
The path and used positions describe the current partial candidate. Each recursive return restores exactly the earlier state.
- 2
Copying the finished path into a tuple matters. Appending the same mutable list reference would make stored results change during later backtracking.
- 3
This version treats positions as distinct. Duplicate input values can produce duplicate value permutations; a multiset-aware search must avoid equivalent branches deliberately.
04 Count the cost
O(n·n!) including materialised permutations
O(n) search state plus O(n·n!) stored output
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Generate all length-two binary strings with recursive choice and undo.
Reveal one possible solution +
result, path = [], []
def visit():
if len(path) == 2:
result.append("".join(path)); return
for bit in "01":
path.append(bit); visit(); path.pop()
visit()
print(result)06 Check your reasoning
Why undo a choice after returning from recursion?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.