Share my elegant solution


  • 1
    L
    class Solution {
    public:
        int fac(int n) {
            int ret = 1;
            for (int i = 1; i <= n; ++i) {
                ret *= i;
            }
            return ret;
        }
    
        string getPermutation(int n, int k) {
            --k;
            string result = "";
            vector <int> nums;
            for (int i = 1; i <= n; ++i) {
                nums.push_back(i);
            }
            for (int i = n - 1; i >= 0; --i) {
                result += nums[k / fac(i)] + '0';
                nums.erase(nums.begin() + k / fac(i));
                k %= fac(i);
            }
            return result;
        }
    };

Log in to reply
 

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