This is essentially the traversal of a decision tree.
There are three things we need to consider:
- Path (or track)
- the list of choices
- End condition
result = []
def backtrack(track, result, choices):
if satisfies_end_condition:
# Here if track is a list we need to do a copy, otherwise we are just appending the pointer to the list's address
result.append(track.copy())
return
for choice in choices:
# Make the choice
track.append(choice)
backtrack(track, result, choices)
# undo the choice (i.e. backtrack)
track.pop()
Reference:
Practice: