Backtracking with choices
Build a candidate one choice at a time and restore the previous state after exploring each branch.
Choose, explore, undo
To build a two-letter sequence from A, B, and C without repeats, choose a first letter, explore possible second letters, and then remove the first choice before trying a different one. If you mutate a shared path, undoing restores exactly the prefix the caller had.
How it works
Pick one choice, update your partial answer, and continue. If that branch is finished or cannot reach a valid result, undo the choice before trying a sibling branch. Record the answer as a copy when later moves would otherwise change it.
Stop when the candidate is complete
Stop a branch when the path has two letters. If a choice would repeat a letter already in the path, skip it. The order of exploration comes from the order of choices, so predictable inputs give predictable outputs. The number of branches can grow rapidly as more positions are added.
Code example
def visit(path):
if len(path) == 2:
print("".join(path))
return
for letter in "ABC":
if letter not in path:
path.append(letter)
visit(path)
path.pop()
visit([])Check your understanding
List every two-letter string with no duplicates, exploring letters in the order given.
See the example and explanation
- Example 1
- Given
A, B, C - Answer
AB, AC, BA, BC, CA, CB - Example 2
- Given
A - Answer
No sequences
With A, B, and C, the A branch emits AB and AC. The B branch emits BA and BC. The C branch emits CA and CB. Each time a branch finishes, restore the prefix before trying the next letter.