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 (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
Three problems:
1. overly dependent on next_permutation, TLE
2. How to rearrange after k/factorial is used
3. k--
Python Version:
class Solution:
def getPermutation(self, n, k):
res = [i+1 for i in range(n)]
fac = [1 for i in range(n+1)]
for i in range(2,n+1):
fac[i] = fac[i-1]*i
k -= 1
for i in range(n):
off,nk = divmod(k,fac[n-1-i])
num = res[i+off]
res[i+1:off+i+1] = res[i:i+off]
res[i] = num
k = nk
return ''.join(str(num) for num in res)
s = Solution()
print(s.getPermutation(3, 3))
C++ version:
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> factorial(n, 1);
string res(n, '1');
for (int i = 1; i < n; ++i) {
factorial[i] = factorial[i-1]*i;
res[i] += i;
}
--k;
for (int i = 0; i < n; ++i) {
int tmp = k / factorial[n - 1 - i];
char ch = res[i + tmp];
for (int j = tmp + i; j > i; --j)
res[j] = res[j - 1];
res[i] = ch;
k = k % factorial[n - 1 - i];
}
return res;
}
};