Share my 0ms c++ program simple and easy to understand


  • 0
    L
    class Solution {
    public:
    	string getPermutation(int n, int k)
    	{
    		if (n <= 0 || k <= 0)return "";
    		string ret;
    		for (int i = 1; i <= n; i++)
    		{
    			ret += to_string(i);
    		}
    		getPermutation(ret, 0, k);
    		return ret;
    	}
    
    private:
    	void getPermutation(string &str, int start, int k)
    	{
    		const int len = str.size() - start;
    		if (len<2||k==1)return;
    		if(k>jiecheng(str.size()))return;
    		if(k==jiecheng(str.size())){reverse(str.begin()+start,str.end());return;}
    		int jc = jiecheng(len - 1);
    		int index = k / jc;
    		if (index!=0)
    		{
    		   	if (k%jc == 0)
    		   	{
    		   	    char temp = *(str.begin() + index + start-1);
    		   	    str.erase(str.begin() + index + start-1);
    			    str.insert(str.begin() + start,temp);
    		   	    reverse(str.begin()+start+1, str.end());
    			    return;
    		   	}
    		   	else
    		   	{
    			    char temp = *(str.begin() + index + start);
    			    str.erase(str.begin() + index + start);
    		 	    str.insert(str.begin() + start,temp);
    		   	}
    		}
    	
    		getPermutation(str, start + 1, k%jc);
    
    	}
    	int jiecheng(int n)
    	{
    		int ret = 1;
    		while (n != 1)
    		{
    			ret *= n;
    			n--;
    		}
    		return ret;
    
    	}
    };

Log in to reply
 

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