The standard recursive solution, self-explanatory


  • 0
    M
    public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        if(nums == null || nums.length == 0) {
            ArrayList<List<Integer>> list = new ArrayList<List<Integer>>();
            ArrayList<Integer> ar = new ArrayList<Integer>();
            list.add(ar);
            return list;
        }
        ArrayList<List<Integer>> list = new ArrayList<List<Integer>>();
        permute(list, nums, 0);
        return list;
    }
    
    private void permute(ArrayList<List<Integer>> list, int[] nums, int start) {
        if(start == nums.length - 1) {
            ArrayList<Integer> ar = new ArrayList<Integer>();
            for(int k = 0; k < nums.length; k++) {
                ar.add(nums[k]);
            }
            list.add(ar);
        }
        for(int k = start; k < nums.length; k++) {
            swap(nums, start, k);
            permute(list, nums, start + 1);
            swap(nums, start, k);
        }
    }
    
    private void swap(int[] nums, int src, int dest) {
        int tmp = nums[src];
        nums[src] = nums[dest];
        nums[dest] = tmp;
    }
    }

  • 0

    This problem require the permutations in lexicographic order, so you answer is not the good one.


  • 0
    M

    it matches the output given in the problem. could you please elaborate? thanks!


  • 0

    when in[] nums = {1,2,3}, the right result is [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]], but your result is [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]]. In lexicographic order, [3,1,2] must before [3,2,1], but your answer is [3,1,2] after [3, 2, 1].


Log in to reply
 

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