How can I improve my code? I feel there will be more elegant solution.


  • 0
    B
    class Solution{
    public:
    	string getPermutation(int n, int k)
    	{
    		k--;//adapt the position of the permutation
    		list<int> a;
    		for(int i=0;i<n;i++)
    		{
    			a.push_back(i+1);
    		}
    		vector<int> result;
    	
    		list<int>::iterator iter;
    		for(int i=0;i<n;i++)
    		{
    			int fac = factorial(n-i-1);
    			int index = k/fac;//get the element index we need
    			k = k%fac;//adjust the position to new situation
    			
    			//add it to the result
    			iter = a.begin();
    			for(int j=0;j<index; iter++,j++) 
    			;
    			result.push_back(*iter);
    			
    			a.erase(iter);//erase the processed element
    		}
    
    		stringstream ss;
    		for(int i = 0;i<n;i++)
    			ss<<result[i];
    		return ss.str();
    	}
    private:
    	int factorial(int i)
    	{
    	if(i==0 || i==1)
    		return 1;
    
    	return i*factorial(i-1);
    }
    };

Log in to reply
 

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