public class Solution {
public String getPermutation(int n, int k) {
int[] A = new int[n];
for(int i = 0; i < n; i++) {
A[i] = i + 1;
}
return kthPermutation(A, n, k);
}
// Cantor expansion
private String kthPermutation(int[] A, int n, int k) {
if(k == 0) {
return "";
}
if(n == 1) {
return "" + A[0];
}
// Gets the first integer
int subFact = factorial(n - 1);
int ind = (k - 1) / subFact;
int init = A[ind];
// Updates A
for(int i = ind; i < n - 1; i++) {
A[i] = A[i + 1];
}
// Recursion
int subK = k % subFact;
if(subK == 0) {
subK = subFact;
}
return "" + init + kthPermutation(A, n - 1, subK);
}
private int factorial(int n) {
if(n == 1) {
return 1;
}
return n * factorial(n - 1);
}
}
Time: O(n^2)
Space: O(n)