Given n and k, return the k-th permutation sequence.
Example
For n = 3
, all permutations are listed as follows:
"123"
"132"
"213"
"231"
"312"
"321"
If k = 4
, the fourth permutation is "231"
class Solution {
/**
* @param n: n
* @param k: the kth permutation
* @return: return the k-th permutation
*/
public String getPermutation(int n, int k) {
String res = "";
k -= 1;
boolean[] s = new boolean[n];
for(int i = n - 1; i >= 0; i--) {
int j = i, tmp = 1;
while(j > 0) {tmp *= j;j--;}
int val = find((int)(k / tmp) + 1, s);
res += val;
s[val - 1] = true;
k %= tmp;
}
return res;
}
int find(int a, boolean[] b) {
int t = 0;
for(int i = 0; i < b.length; i++) {
if(b[i] == false) {
t += 1;
if(t == a) return i + 1;
}
}
return -1;
}
}