Given a list of unique letters, find all of its distinct permutations.
['a', 'b', 'c']
[['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]
Try it yourself
Classic combinatorial search problem, let's apply the 3-step system from backtracking template.
1. Identify states
What state do we need to know whether we have reached a solution (and using it to construct a solution if the problem asks for it).
- We need a state to keep track of the list of letters we have chosen for the current permutation
What state do we need to decide which child nodes should be visited next and which ones should be pruned.
- We have to know what are the letters left that we can still use (since each letter can only be used once).
2. Draw the State-space Tree
3. DFS on the State-space tree
Using the backtracking template as basis, we add the two states we identified in step 1:
- A list to represent permutation constructed so far,
- A list to record which letters are already used,
used[i] == truemeans
ith letter in the origin list has been used.
Feel free to revisit the DFS on tree animation to gain more intuition on how the code works with call stack.
Notice how similar the solution is to Ternary Tree Paths. The difference is we have a new constraint "number of letters left" while deciding which subtree goes down to.
Note on deep copy
In the exit logic of the above solution, we append a deep copy of path
res.append(path[:]). This creates a new list with elements being the same as current elements of
path. Consider what happens if we don't make the deep copy:
>>> res =  >>> path =  >>> for i in range(3): ... path.append(i) ... res.append(path) ... >>> res [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
We get the same copy three times! Because
append(path) actually appends a reference (memory address), we actually appended the same list three times.
path.append(i) mutates the list and affects all references to that list. To fix this, we create a new list before we append.