08.07. Permutation I
Description
Write a method to compute all permutations of a string of unique characters.
Example1:
Input: S = "qwe" Output: ["qwe", "qew", "wqe", "weq", "ewq", "eqw"]
Example2:
Input: S = "ab" Output: ["ab", "ba"]
Note:
- All characters are English letters.
1 <= S.length <= 9
Solutions
Solution 1: DFS (Backtracking)
Thinking
All permutations of a string with distinct characters are required. The \(n!\) size matches the output lower bound.
Fill positions left to right from unused characters, tracked by \(vis\).
\(dfs(i)\) writes an unused index of \(S\) into \(t[i]\) and records a string at \(i=n\). Unmarking on the way back emits each permutation once.
We design a function \(\textit{dfs}(i)\) to represent that the first \(i\) positions have been filled, and now we need to fill the \((i+1)\)-th position. Enumerate all possible characters, and if the character has not been used, fill in this character and continue to fill the next position until all positions are filled.
The time complexity is \(O(n \times n!)\), where \(n\) is the length of the string. There are \(n!\) permutations in total, and each permutation takes \(O(n)\) time to construct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |