Permutation Sequence
The set[1,2,3,…,n]contains a total ofn! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, forn= 3):
"123""132""213""231""312""321"
Givennandk, return thekthpermutation sequence.
public class Solution {
public String getPermutation(int n, int k) {
int[] f = new int[n + 1];
f[0] = 1;
for(int i = 1; i <=n; i ++) {
f[i] = f[i-1] * i;
}
List<String> seq = new ArrayList<>();
for(int i = 1; i <= n; i ++){
seq.add(i+"");
}
k --;
StringBuilder res = new StringBuilder();
for(int i = 1; i <= n; i ++) {
int index = k / f[n - i];
res.append(seq.get(index));
seq.remove(index);
k %= f[n - i];
}
return res.toString();
}
}