My C++ solution for Permutation Sequence.


  • 0
    G
    class Solution {
    public:
        string getPermutation(int n, int k) {
            string str="123456789";
            
            vector<int> table(n,1);
            for(int i=1;i<n;i++){
                table[i]=table[i-1]*(i+1);
            }
            string result;
            int kk=k-1;
            while(n!=0){
                if(n==1){result.push_back(str[0]);break;}
                int a=(kk)/table[n-2];
                result.push_back(str[a]);
                str.erase(str.begin()+a);
                kk=(kk)%table[n-2];
                n--;
            }
            return result;
        }
    };

Log in to reply
 

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