2ms java solution based on swap and recursion


  • 1
    Q
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> cur = new ArrayList<Integer>();
        for (int num : nums) cur.add(num);
        res.add(cur);
        permute(nums, nums.length, 0, res);
        return res;
    }
    private void permute(int[] nums, int n, int index, List<List<Integer>> res){
        if (index + 1 < n - 1) permute(nums, nums.length, index + 1, res); // situation 1: the "index" element doesn't change
        for (int i = index + 1; i < n; i++){ // situation 2: swap "index" element with each element after it
            swap(nums, index, i);
            List<Integer> list = new ArrayList<Integer>();
            for (int num : nums) list.add(num);
            res.add(list);
            permute(nums, n, index + 1, res);
            swap(nums, i, index);
        }
    }
    private void swap(int[] nums, int i, int j){
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }

Log in to reply
 

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