C++ 0ms observation solution


  • 3
    F
    class Solution {
    public:
        string getPermutation(int n, int k) {
            int mloop[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
            string ans;
            vector<int> remain;
            for (int i = 1; i <= n; ++i) {
                remain.push_back(i);
            }
            for (int i = n; i > 0; --i) {
                int j = ((k - 1) % mloop[i]) / mloop[i - 1];
                ans += (remain[j] + '0');
                remain.erase(remain.begin() + j);
            }
            return ans;
        }
    };
    
    ()1234           (1)234         (12)34        (123)4
    1 1234           1 234           1 34     =>    1 4
    2 1243           2 243     =>    2 43
    3 1324           3 324
    4 1342  =>       4 3....
    5 1423
    6 1432
    7 2134
    8 2......

Log in to reply
 

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