Share my simple 3ms Java recursive algorithm:


  • 0
    Z
    public String getPermutation(int n, int k) {
        ArrayList<Integer> list = new ArrayList<Integer>(n);
        for(int i=1;i<=n;i++){
            list.add(i);
        }
        return getPermutation(list, k-1, "");
    }
    
    private String getPermutation(ArrayList<Integer> list, int k, String progress){
        if(list.size() == 1){
            return progress+list.get(0);
        }
        int grid = factorial(list.size()-1);
        int index = k/grid;
        int digit = list.get(index);
        progress = progress + digit;
        list.remove(index);
        return getPermutation(list,k-grid*index, progress);
    }

Log in to reply
 

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