Backtracking
When to use: "generate all …" (subsets, permutations, combinations, partitions, boards). Explore a decision tree depth-first: choose → recurse → un-choose.
def backtrack(start, path):
if is_solution(path):
res.append(path[:]) # copy!
return # (subsets: record at every node, no return)
for i in range(start, len(choices)):
if i > start and choices[i] == choices[i - 1]:
continue # skip duplicates (sorted input)
path.append(choices[i])
backtrack(i + 1, path) # i -> reuse allowed; i+1 -> each used once
path.pop()
subsets of [1,2,3] []
/ | \
[1] [2] [3]
/ \ |
[1,2] [1,3] [2,3]
|
[1,2,3]
| Problem type | start index | dedupe | used[] |
|---|---|---|---|
| Subsets / combinations | i + 1 | sort + skip i > start dup | – |
| Combination sum (reuse) | i | – | – |
| Permutations | 0 | sort + skip if prev dup unused | yes |
Problems
Showing 23 of 23