Accepted Recursive Solution in Java


  • 9
    H
    int len;
    boolean[] used;
    List<List<Integer>> result;
    List<Integer> temp;
    public List<List<Integer>> permute(int[] num) {
        len = num.length;
        used = new boolean[len];
        result = new ArrayList<List<Integer>>();
        temp = new ArrayList<>();
        doPermute(num, 0);
    
        return result;
    }
    
    public void doPermute(int[] in, int level) {
        if (level == len) {
            result.add(new ArrayList<Integer>(temp));
            return;
        }
    
        for (int i = 0; i < len; i++) {
            if (used[i]) {
                continue;
            }
    
            temp.add(in[i]);
            used[i] = true;
            doPermute(in, level + 1);
            used[i] = false;
            temp.remove(level);
        }
    }

Log in to reply
 

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