C++ easy-understanding iterative


  • 0
    X
    class Solution {
    public: 
        string getPermutation(int n, int k) {
            string ans;
            vector<int> f(n + 1, 1);
            vector<char> index(n);
            int i = 1;
            for_each(index.begin(), index.end(), [&i](char& x){x = '0' + i++;});
            for(int i = 1; i <= n; ++i){
                f[i] = f[i - 1] * i;
            }
            --k;
            for(int i = 1; i <= n; ++i){
                int idx = k / f[n - i];
                ans.insert(ans.end(), index[idx]);
                index.erase(index.begin() + idx);
                k -= f[n - i] * idx;
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.