My 4ms C++ solution


  • 0
    T
    class Solution {
    private:
        int factorial(int n)
        {
            int result=1;
            int i;
            for(i=1; i<=n; i++)
                result=result*i;
            return result;
        }
    public:
        string getPermutation(int n, int k) {
            string s;
            int i;
            int K = k-1;
            int base;
            int index;
            vector<int> nums;
            for(i=1; i<=n; i++)
                nums.push_back(i);
            for(i=n; i>=1; i--)
            {
                base = factorial(i-1);
                index = K/base;
                K = K%base;
                s = s + to_string(nums[index]);
                nums.erase(nums.begin()+index);
            }
            return s;
        }
    };

Log in to reply
 

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