Share my Java AC solution


  • 1
    I

    Perhaps @ceilfors has already explained the method pretty well : https://leetcode.com/discuss/55418/java-clean-code-two-recursive-solutions

    Here is one solution which doesn't use a variable to keep track of the length, but rather use the size of sublist as length indicator and much shorter and easier to understand.

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        if(nums == null || nums.length == 0 ) return list;
        backtrack(list, new ArrayList<>(), nums);
        return list;
    }
    
    private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
        if(tempList.size() == nums.length){
            list.add(new ArrayList<>(tempList));
        } else{
            for(int i = 0; i <= tempList.size(); i++){
                tempList.add(i, nums[tempList.size()]);
                backtrack(list, tempList, nums);
                tempList.remove(i);
            } 
        }
    }

Log in to reply
 

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