Backtracking problems - my approach that works every time
After struggling with backtracking for weeks, I developed this mental framework:
- What are my choices at each step?
- What constraints must I satisfy? (when to prune)
- What does the base case look like? (when am I done)
Then the template is always:
def backtrack(current_state, choices_left):
if is_solution(current_state):
save_result()
return
for choice in choices_left:
if is_valid(choice):
make_choice()
backtrack(new_state, remaining_choices)
undo_choice()
This worked for: N-Queens, Sudoku, Permutations, Subsets, Combination Sum, Word Search, and Palindrome Partitioning.
Hope this helps someone!