Java iterative solution.


  • 1
    C
    public String getPermutation(int n, int k) {
        List<Integer> nums = new LinkedList<>();
        for (int i = 1; i <= n; i++) {
            nums.add(i);
        }
        String ret = "";
        k--;
        while (!nums.isEmpty()) {
            int f = fact(n-1);
            int i = k / f;
            ret += nums.get(i).toString();
            nums.remove(i);
            k -= k/f*f;
            n--;
        }
        return ret;
    }
    
    private int fact(int n) {
        int ret = 1;
        for (int i = 1; i <= n; i++) {
            ret *= i;
        }
        return ret;
    }

Log in to reply
 

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