A 3ms C++ Iterative Solution


  • 0
    Y
    class Solution {
    public:
        string getPermutation(int n, int k) {
            int total = 1;
            for(int i = 1; i <= n; i++) total *= i;
            
            int d = k - 1;
            string ans = "", charPool = "123456789";
            
            for(int j = n; j > 0; j--) {
                total /= j;
                ans += charPool[d/total];
                charPool.erase(d/total,1);
                d = d%total;
            }
            return ans;
        }
    };

Log in to reply
 

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