My 4ms C++ solution


  • 0
    B
    string getPermutation(int n, int k)
    {
        k -= 1;
        int factor = 1;
        vector<char> a;
        for (int i = 1; i < n; i++)
        {
            factor *= i;
            a.push_back(i+'0');
        }
        a.push_back(n+'0');
    
        int boundary = n-1;
        string result;
        while (k > 0)
        {
            int temp = k/factor;
            result += a[temp];
            a.erase(a.begin()+temp);
    
            k %= factor;
            factor /= boundary;
            boundary -= 1;
        }
    
        int len = a.size();
        for (int i = 0; i < len; i++) 
        {
            result += a[i];
        }
    
        return result;
    }

Log in to reply
 

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