Super short recursive Java solution


  • 0
    C
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        permute(Arrays.stream(nums).boxed().collect(Collectors.toList()), 0, res); //int[] 2 List<Integer>
        return res;
    }
    
    public void permute(List<Integer> nums, int i, List<List<Integer>> res) {
        if (i == nums.size()) res.add(nums);
        else
            for (int j = i; j < nums.size(); j++) {
                Collections.swap(nums, i, j);
                permute(new LinkedList<Integer>(nums), i + 1, res);
                Collections.swap(nums, i, j);
            }
    }

Log in to reply
 

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