Leetcode 60 Solution

This article provides solution to leetcode question 60 (permutation-sequence)

https://leetcode.com/problems/permutation-sequence

Solution

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> a(n);
        vector<int> b(n + 1);
        b[0] = 1;

        k--;

        for (int i = 1; i <= n; i++)
        {
            a[i - 1] = i;
            b[i] = b[i - 1] * i;
        }

        for (int i = 0; i < n; i++)
        {
            if (k >= b[n - 1 - i])
            {
                int shift = k / b[n - 1 - i];

                int target = a[i + shift];
                for (int j = i + shift; j > i; j--)
                    a[j] = a[j - 1];
                a[i] = target;

                k = k % b[n - 1 - i];
            }
        }

        string res;
        for (int i = 0; i < n; i++)
            res += to_string(a[i]);

        return res;
    }
};