Sharing my 4ms C++ code


  • 0
    Z
    #include <algorithm>
    #include <vector>
    #include <sstream>
    
    class Solution {
    public:
        string getPermutation(int n, int k) {
            string res;
            vector<int> ans;
            if(n<1 || n>9)
            return res;
    	    int total=n;
    	    int temp,temp_fac;
            for(int j=0;j<total;j++){
                n=n-1;
                temp_fac=fac(n);
                temp=(k-1)/temp_fac+1;
                k=(k-1)%temp_fac+1;
                for(int i=0;i<j;i++){
                    if(temp>=ans[i])
                    temp++;
                }
                res.push_back('0'+temp);//use this to modify the low performance of sstream
                ans.push_back(temp);
                sort(ans.begin(),ans.end());
            }
    	return res;
        }
        
        int fac(int n){
            if(n<2)
            return 1;
            else
            return n*fac(n-1);
        }
    };

Log in to reply
 

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