60. Permutation Sequence(js)

60. Permutation Sequence

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:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note:

  • Given n will be between 1 and 9 inclusive.
  • Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"
题意:返回数组的第k个全排列的字符串形式
代码如下:
/**
 * @param {number} n
 * @param {number} k
 * @return {string}
 */
var getPermutation = function(n, k) {
    let res='';
    let arr='123456789'.split('');
    let f=[];
    f[0]=1;
    for(let i=1;i<n;i++){
        f[i]=f[i-1]*i;
    }
    k--;
    for(let i=n;i>=1;i--){
        let j=parseInt(k/f[i-1]);
        k%=f[i-1];
        res+=arr[j];
        arr.splice(j,1);
    }
    return res;
};

 

posted @ 2019-03-01 20:17  mingL  阅读(174)  评论(0编辑  收藏  举报