Just need to be careful


  • 0
    public class Solution {
        public String getPermutation(int n, int k) {
            List<Integer> list = new ArrayList<>();
            for (int i = 1; i <= n; i++) list.add(i);
            
            if (k <= 0) return "";
            k--;
            
            int factorial = 1;
            for (int i = 2; i < n; i++) factorial *= i;
            
            String res = "";
            int m = n - 1;
            while (m > 0) {
                int index = k / factorial;
                res += list.remove(index);
                k -= index * factorial;
                factorial /= m; 
                m--;
            }
            res += list.get(0); 
            return res;
        }
    }
    

Log in to reply
 

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