Permutation Sequence
2018-08-15 本文已影响0人
斯特莫
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 for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
分析: 每一位数字出现的次数是后面n个数字的全排列, 就是n!. 按照这个规律向后以k=k/n!的方式递减k就能求出所有的数.
var getPermutation = function(n, k) {
let res = '';
let nums = [];
for(let i = 0; i < n; i++){
nums.push(i+1);
}
k--;//因为factorial(0)的值设为了1, 防止k=1, n=1情况下k一直等于1的情况
for(let i = n; i >= 1; i--) {
let index = parseInt(k / factorial(n-1));
k = k % factorial(n-1);
res = res + nums[index];
nums.splice(index,1);
}
return res;
};
var factorial = function(n) {
if(n==0){
return 1;
}
let res = n;
for(let i = n - 1; i > 0; i--) {
res = res * i;
}
return res;
};