给定 n 和 k,求123..n组成的排列中的第 k 个排列。
class Solution {
public:
    string getPermutation(int n, int k) {
        string res;
        vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        fun(vec, n, k, res); 
        return res;
    }
    void fun(vector<int>& vec, int n, int k, string& res) {
        if (n == 1) {
            res += to_string(vec.front());
            return;
        }
        
        int sum = 1;
        for (int i = 2; i < n; ++i) {
            sum *= i;
        }
        
        int idx = (k - 1) / sum; // k - 1
        
        res += to_string(vec[idx]);
        k -= idx * sum;
        vec.erase(vec.begin() + idx);
        fun(vec, n - 1, k, res);
    }
};

shiyang6017
158 声望59 粉丝