Easy c++ solution


  • 1
    I
    class Solution {
    public:
        string getPermutation(int n, int k) {
            vector<int> vec(n);
            string str = "";
            for(int i = 0; i < n; i++) {
                vec[i] = i + 1;
            }
            int permutation[n+1];
            permutation[0] = 1;
            for(int i = 1; i <= n; i++) {
                permutation[i] = permutation[i-1] * i;
            }
            for(int i = n; i >= 1; i--) {
                int count = 1;
                while(k > permutation[i-1]) {
                    k -= permutation[i-1];
                    count++;
                }
                str = str + to_string(vec[count-1]);
                vec.erase(vec.begin()+count-1);
            }
            return str;
        }
    };
    

Log in to reply
 

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