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

原文地址:https://www.cnblogs.com/argenbarbie/p/5267654.html