Excellent java solution with recursion


  • 0
    H

    public class Solution {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        permutation(nums, 0, nums.length - 1, list);
        return list;
    }
    public void permutation(int[] nums, int k, int m, List<List<Integer>> list) {
        if(k == m) {
            List<Integer> perm = new ArrayList<>();
            for(int i = 0; i < nums.length; i++) {
                perm.add(nums[i]);
            }
            list.add(perm);
        } else {
            for(int j = k; j <= m; j++) {
                swap(nums, j, k);
                permutation(nums, k + 1, m, list);
                swap(nums, j, k);
            }
        }
    }
    public void swap(int[] nums, int j, int k) {
        int l = nums[k];
        nums[k] = nums[j];
        nums[j] = l;
    }
    

    }


Log in to reply
 

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