Permutations

Prereq: Backtracking

Given a list of unique letters, find all of its distinct permutations.

Input:

['a', 'b', 'c']

Output:

[['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]

Try it yourself

Explanation

Intuition

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).

  1. 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.

  1. 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:

  1. A list to represent permutation constructed so far, path
  2. A list to record which letters are already used, used, used[i] == true means ith letter in the origin list has been used.
1
1
def permutations(l):
2
-
    # WRITE YOUR BRILLIANT CODE HERE
2
+
    def dfs(path, used, res):
3
+
        if len(path) == len(l):
4
+
            res.append(path[:]) # note [:] make a deep copy since otherwise we'd be append the same list over and over
5
+
            return
6
+
7
+
        for i, letter in enumerate(l):
8
+
            # skip used letters
9
+
            if used[i]:
10
+
                continue
11
+
            # add letter to permutation, mark letter as used
12
+
            path.append(letter)
13
+
            used[i] = True
14
+
            dfs(path, used, res)
15
+
            # remove letter from permutation, mark letter as unused
16
+
            path.pop()
17
+
            used[i] = False
18
+
19
+
    res = []
20
+
    dfs([], [False] * len(l), res)
21
+
    return res
22
+
3
23
if __name__ == "__main__":
4
24
    res = permutations(list(input()))
5
25
    print(' '.join(sorted(''.join(x) for x in res)))

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.