My mathematical cpp solution


  • 0
    C
    class Solution {
    public:
        int factorial(int n)
        {
            int result = 1;
            for(int i=1; i<=n; i++)
                result *= i;
                
            return result;
        }
    
        string getPermutation(int n, int k) 
        {
            string result;
            
            vector<int> nums;
            for(int i=1; i<=n; i++)
                nums.push_back(i);
            
            int perm_cnt_of_bitnum = factorial(n);
            
            for(int bit = n; bit >= 1; bit--)
            {
                perm_cnt_of_bitnum /= bit;
                
                int digit = (k-1) / perm_cnt_of_bitnum;
                
                result.push_back('0' + nums[digit]);
                
                nums.erase(nums.begin() + digit);
                
                k = k - digit * perm_cnt_of_bitnum;
            }
            
            return result;
        }
    };

Log in to reply
 

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