Permutations with backtracking in Python
Backtracking builds every arrangement of the letters by choosing a letter, filling the remaining places the same way, then undoing the choice so the next letter can take that place.
The arrow keys step through it. Edit the code to try your own input.
How it works
pathholds the letters chosen so far, andused[i]says whetherletters[i]is already in it.- For each letter that is not used yet, choose it: mark it in
usedand add it topath. Then callpermuteto fill the remaining places. - When
pathis as long asletters, one full arrangement is saved inresults. - After the call returns, undo the choice with
path.pop()andused[i] = False, so the next letter can be tried in that place. That undo is the backtracking.
What to watch
- Watch every
permuteframe point at the samepathandusedlists: there is only one of each, changed and then restored. - Watch the call stack grow to four
permuteframes whenpathis full, then shrink as the search backs up. - Watch
resultsgain a new arrangement each time the stack is at its deepest.
The code
letters = "abc" results = [] def permute(path, used): if len(path) == len(letters): results.append("".join(path)) # a full arrangement return for i in range(len(letters)): if used[i]: continue # already in path used[i] = True # choose path.append(letters[i]) permute(path, used) # explore path.pop() # un-choose: backtrack used[i] = False permute([], [False] * len(letters)) print(results)
Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Open it in the editor · Python Program to Print All Permutations of a String, explained