LeetCode OJ 60. Permutation Sequence

时间:2023-03-10 07:16:55
LeetCode OJ 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):

"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.

解答

这里用到按序排列的一个性质,就是长度为n的数列的第k个排列的最高位,等于这个数列中的第ceil(k / (n - 1)!)位.

下面是AC的代码:

class Solution {
public:
    long long fac(int n){
        int ret = 1;
        while(n > 1){
            ret *= n;
            n--;
        }
        return ret;
    }
    string getPermutation(int n, int k) {
        long long total = fac(n);
        vector<int> left;
        string ans;
        int length, temp, digit;

        for(int i = 1; i <= n; i++){
            left.push_back(i);
        }
        for(int i = n; i > 0; i--){
            total /= i;
            temp = k / total;
            if(k != temp * total){
                digit = left[temp];
                left.erase(left.begin() + temp);
            }
            else{
                digit = left[temp - 1];
                left.erase(left.begin() + temp - 1);
            }
            ans = ans + to_string(digit);
            if(k != temp * total){
                k -= temp * total;
            }
            else{
                k -= (temp - 1) * total;
            }
        }
        return ans;
    }
};

112