首页 > 代码库 > LeetCode Permutation Sequence

LeetCode Permutation Sequence

class Solution {
public:
    string getPermutation(int n, int k) {
        k--;
        if (n < 1 || k < 0) return "";

        vector<int> nums(n, 0);
        long seg = 1;
        for (int i=0; i<n; i++) {
            nums[i] = i + 1;
            seg = seg * (nums[i]);
        }
        if (k >= seg) return "";    
        int idx = 0;

        for (int i=0; i < n-1; i++) {
            seg = seg / (n - i);
            idx = k / seg + i;
            k = k % seg;

            int sel = nums[idx];

            for (int j = idx; j>i; j--) {
                nums[j] = nums[j - 1];
            }

            nums[i] = sel;
        }
        string res;
        for (int i=0; i<n; i++) {
            res.push_back((char)(nums[i] + 0));
        }
        return res;
    }
};

复杂度O(n^2), 但是因为参数k用int表示了,说明n的值不会太大,否则n!(k最大值)轻轻松松超过int范围