My 0ms C++ code


  • 0
    Q
     string getPermutation(int n, int k) {
    	int factor[10] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
    	int pre;
    	string s;
    	string ans;
    	for (int i = 1; i <= n; i++)
    	{
    		char a = '0' + i;
    		s = s + a;
    	}
    	if (k == 1)
    		return s;
    	for (int i = 0; i<n; i++)
    	{
    		pre = factor[n - i - 1];
    		int code = ceil(k *1.0/ pre);
    		k = k-(code-1)*pre;
    		
    		ans.push_back(s[code - 1]);
    		s.erase(s.begin() + code - 1);
    	}
    	return ans;
    }

Log in to reply
 

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