LeetCode 60.排列序列

60. 排列序列 - 力扣(LeetCode)

做法一:用c++中自带的next_permutation来做,在这里是不会超时的

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;
    }   
};

做法二:通过定位k所在区间来做

class Solution {
public:
    string getPermutation(int n, int k) {
        string res;
        vector<bool> st(10);

        for(int i = 0; i < n; i ++ ) {
            int fact = 1;
            for(int j = 1; j <= n - i - 1; j ++ ) fact *= j;

            for(int j = 1; j <= n; j ++ ) {
                if(!st[j]) {
                    if(fact < k) k -= fact;
                    else {
                        res += to_string(j);
                        st[j] = true;
                        break;
                    }
                }
            }
        }
        return res;
    }
};

你可能感兴趣的:(LeeCode系统刷题之旅,leetcode,算法,c++)