60. Permutation Sequence

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 (ie, 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.

string getPermutation(int n, int k) {
    int total=1, idx, i;
    vector<char> nums;
    for(i = 1; i <= n; i++)
    {
        nums.push_back(i+0);
        total *= i;
    }
    if(k>total || k<1)
        return "";
    string s;
    s.resize(n);
    i = 0;
    while(n)
    {
        total /= n;
        idx = (k-1) / total;
        s[i++] = nums[idx];
        nums.erase(nums.begin()+idx);
        k = (k-1) % total +1; //can also be k -= group * idx
        n--;
    }
    return s;
}

// Construct the k-th permutation with a list of n numbers
// Idea: group all permutations according to their first number (so n groups, each of
// (n-1)! numbers), find the group where the k-th permutation belongs, remove the common
// first number from the list and append it to the resulting string, and iteratively
// construct the (((k-1)%(n-1)!)+1)-th permutation with the remaining n-1 numbers

以上是关于60. Permutation Sequence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(60):Permutation Sequence

LeetCode31 Next Permutation and LeetCode60 Permutation Sequence

60. Permutation Sequence

60. Permutation Sequence

Permutation Sequence LT60

60. Permutation Sequence