4ms accepted c++ code


  • 0
    J
    string getPermutation(int n, int k) {
        if(k>factorial(n)) return "";
        if(n==1 && k==1) return "1";
        string result;
        vector<int> remain;
        for(int i=0; i<n; i++) remain.push_back(i+1);
        while (n>1) {
            result += to_string(remain[(k-1)/factorial(n-1)]);
            remain.erase(remain.begin()+(k-1)/factorial(n-1));
            k = (k-1)%factorial(n-1) + 1;
            n--;
        }
        result += to_string(remain[0]);
        return result;
    }
    
    int factorial(int n) {
        int result = 1;
        while (n>0) {
            result *= n;
            n--;
        }
        return result;
    }

Log in to reply
 

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