Java Recursive Solution Using ArrayList


  • 0
    I
     public String getPermutation(int n, int k) {
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            list.add(i);
        }
        return helper(k - 1, list);
    }
    
    public String helper(int k, List<Integer> list) {
        StringBuffer sb = new StringBuffer();
        if (list.size() == 0) {
            return sb.toString();
        }
        int num = 1;
        int i = 1;
        int n = list.size();
        for (; i <= n; i++) {
            num *= i; 
            if (num > k) {
                break;
            }
        }
        if (i == n + 1) {
            i--;
        }
        for (int j = n; j >= i + 1; j--) {
            sb.append(list.remove(0));
        }
        num /= i;
        int idx = k / num;
        sb.append(list.remove(idx));
        sb.append(helper(k - idx * num, list));
        return sb.toString();
    }

Log in to reply
 

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