The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
Example 3:
Input: n = 3, k = 1
Output: "123"
Constraints:
1 <= n <= 9
1 <= k <= n!
Solutions
Solution 1: Enumeration
Thinking
The first idea is to generate all \(n!\) permutations and pick the \(k\)-th. \(n \le 9\), so \(9!\) would pass, but we never need the other permutations.
The waste is listing then selecting. After the first digit is fixed, the rest form \((n-1)!\) permutations; comparing \(k\) with that block size tells us which unused number goes here.
So we enumerate each position left to right, skip whole blocks with factorials, and mark used numbers in \(\textit{vis}\). Time \(O(n^2)\).
We know that the set \([1,2,..n]\) has a total of \(n!\) permutations. If we determine the first digit, the number of permutations that the remaining digits can form is \((n-1)!\).
Therefore, we enumerate each digit \(i\). If \(k\) is greater than the number of permutations after the current position is determined, then we can directly subtract this number; otherwise, it means that we have found the number at the current position.
For each digit \(i\), where \(0 \leq i < n\), the number of permutations that the remaining digits can form is \((n-i-1)!\), which we denote as \(fact\). The numbers used in the process are recorded in vis.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n)\).