leetcode--47. Permutations II

1、问题描述

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

2、边界条件:无,空数组也可以统一处理

3、思路:递归,先排序方便去重。然后跟正常排列一样,加一个去重操作。特别注意5种失效的方法。

4、代码实现

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        Arrays.sort(nums);
        List<Integer> numList = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            numList.add(nums[i]);
        }
        permuteUnique(results, new ArrayList<Integer>(), numList);
        return results;
    }

    public void permuteUnique(List<List<Integer>> results, List<Integer> cur,
                              List<Integer> numList) {
        if (0 == numList.size()) {
            List<Integer> result = new ArrayList<>(cur);
            results.add(result);
            return;
        }
        for (int i = 0; i < numList.size(); i++) {
            if (i != 0 && numList.get(i) == numList.get(i - 1)) {
                continue;
            }
            cur.add(numList.get(i));//这种result可以用int[]试一下
            numList.remove(i);
            permuteUnique(results, cur, numList);
            numList.add(i, cur.get(cur.size() - 1));
            cur.remove(cur.size() - 1);
        }
    }
}

 

5、一种在无重复数字情况下有效,在有重复数字的情况下失效的方法

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        Arrays.sort(nums);
        permuteUnique(results, nums, 0);
        return results;
    }

    public void permuteUnique(List<List<Integer>> results,
                              int[] nums, int index) {
        if (index == nums.length) {
            List<Integer> result = new ArrayList<>();
            for (int i = 0; i < index; i++) {
                result.add(nums[i]);
            }
            results.add(result);
            return;
        }
        for (int i = index; i < nums.length; i++) {
            if (i != index && nums[i] == nums[i - 1]) {
                continue;
            }
            swap(nums, i, index);//问题出来这里,改变了数组的结构,使得数组变得无序。
            permuteUnique(results, nums, index + 1);
            swap(nums, i, index);
        }
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

if (i != index && nums[i] == nums[i - 1]),这个判断在不改边数组结构的情况下是可以达到去重目的的。但是我这里用的方法改变了nums的结构,使得主函数里面sort好的nums又变成无序,从而去不了重。就拿[0, 1, 0, 0, 9]来说,排好序之后[0, 0, 0, 1, 9],在index=0时,交换0<-->9,变成[9, 0, 0, 1, 0],变得无序,使得去重方法失效。需要再把顺序调整下,但是恢复不了。所以在有重复数字的情况下这个改变nums结构的方法不能用。

6、api

posted on 2017-08-31 22:20  Shihu  阅读(212)  评论(0编辑  收藏  举报

导航