Backtracking Patterns
Backtracking Patterns
Backtracking is depth-first search over choices.
Template
def backtrack(path, choices):
if done(path):
collect(path)
return
for choice in choices:
if not valid(choice, path):
continue
path.append(choice)
backtrack(path, next_choices(choice))
path.pop()
Practice
- Target Sum Ways
- Partition Labels (greedy alternative to explore boundaries)