Share my simple C++ method


  • 0
    X

    int factoral[10]={1,1,2,6,24,120,720,5040,40320,362880};

    class Solution {
    public:
    string getPermutation(int n, int k) {
    string s(n,'1');
    for(int i=1;i<n;i++) s[i]=i+1+'0';
    int cur=1;

    	if(k==1) return s;
    
    	while(cur<k){
    		int i=1;
    		while(cur + factoral[i]<k) i++;
    		if(cur+factoral[i]>k) i--;
    		int ii=n-i-1;
    		int j=ii+1;
    		while(j<n and s[j]<s[ii]) j++;
    		char tmp=s[j]; s[j]=s[ii]; s[ii]=tmp;
    		sort(s.begin()+ii+1, s.end());
    		cur=cur + factoral[i];
    	}
    
    	return s;
    }
    

    };


Log in to reply
 

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