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.
/**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getPermutation = function(n, k) {
var numsArr = ['1','2','3','4','5','6','7','8','9'],
factorialArr = [1,1,2,6,24,120,720,5040,40320,362880],
res = '';
for(var i = n; i > 0; i--) {
var j = Math.ceil(k/factorialArr[i-1]) - 1;
res+=(numsArr[j]);
numsArr.splice(j, 1);
k = (k-1) % factorialArr[i - 1] + 1;
}
return res;
};
康托展开公式