60. 排列序列(LeetCode困难)(递归排序)

60. 排列序列

使用next_permutation O(n!k)

class Solution {
public:
    string getPermutation(int n, int k) {
        string res;
        for(int i = 1; i <= n; ++i) res += to_string(i);
        for(int i = 0; i < k - 1; ++i){
            next_permutation(res.begin(), res.end());
        }

        return res;
    }
};
class Solution {
public:
    string getPermutation(int n, int k) {
        string res;
        vector<bool> st(10, 0);
        for(int i = 0; i < n; ++i){
            //该位每填一个数字,都会有fact个数
            int fact = 1;
            for(int j = 1; j <= n - i - 1; ++j) fact *= j;
            //枚举没有被用过的数字
            for(int j = 1; j <= n; ++j){
                if(!st[j]){
                    //看一下第k个数是否在j这一组里面
                    if(fact < k) k -= fact;
                    else{
                        res += to_string(j);
                        st[j] = true;
                        break;
                    }
                }
            }
        }

        return res;
    }
};
posted @ 2025-03-12 21:43  awei040519  阅读(20)  评论(0)    收藏  举报