My accepted Java Solution


  • 0
    public class Solution {
        public String getPermutation(int n, int k) {
            StringBuilder res = new StringBuilder();
            ArrayList<Integer> nums = new ArrayList<Integer>();
            int remain = n;
            int[] fac = new int[n];
            for (int i = 0; i < n; i++) {
                if (i == 0) {
                    fac[i] = 1;
                } else {
                    fac[i] = fac[i - 1] * (i + 1);
                }
                nums.add(i + 1);
            }
            k--;
            while (k > 0) {
                int index = k / fac[remain - 2];
                res.append(nums.get(index));
                nums.remove(index);
                k = k % fac[remain - 2];
                remain--;
            }
    
            for (int i = 0; i < nums.size(); i ++) {
                res.append(nums.get(i));
            }
            return res.toString();
        }
    }

Log in to reply
 

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