My C++ iterative solution for reference, easy to read.


  • 0
    E
    class Solution {
    public:
        string getPermutation(int n, int k) {
    	vector<int> a;
    	vector<int> b;
    	string s;
    	for (int i = 0; i < n; i++) 
    	  a.push_back(i + 1);
    
    	k = k - 1;
    	while (n>1) {
    	  int f = fab(--n);
    	  b.push_back(a[k/f]);
              a.erase(a.begin()+k/f); // remove element used
    	  k = k % f;
    	}
    	b.push_back(a[0]);
    	for (int i = 0; i < b.size(); i++)
    	  s = s + (char)(b[i] + '0');
    	return s;
        }
       int fab(int n) {
    	if (n == 1) return 1;
    	else return n*fab(n - 1);
       }    
    };
    
    

Log in to reply
 

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