share my recursive solution


  • 0
    E
    class Solution {
        public String getPermutation(int n, int k) {
        
            // make factorial search table;  
            int[] facl = new int[n+1];
            facl[1] = 1;
            for (int i = 2; i < n+1; i++) facl[i] = i*facl[i-1];
            
            String res = new String();
            if (n == 0 || k > facl[n]) return res;
            
            List<Integer> nums = new ArrayList<Integer>();
            for (int i = 1; i <= n; i++) nums.add(i);
            
            int lastPo = 0;
            int m = 0;
            while (res.length() < n-1) {
                k -= lastPo * facl[n - m];
                int i = (k-1) / facl[n - m - 1];
                res += nums.remove(i);
                lastPo = i;
                m++;
            }
            return res + nums.remove(0);   
        }
    }

Log in to reply
 

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