47 Permutations II

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]
]

分析及代码

和46差不多,但是如果两个连续的数是一样的,并且前一个没有使用的话,后一个也没有必要尝试了,避免重复

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        generate(res, new ArrayList<>(), nums, used);
        return res;
    }

    private void generate(List<List<Integer>> res, List<Integer> item, int[] nums, boolean[] used) {
        if(item.size() == nums.length) {
            res.add(new ArrayList<>(item));
            return;
        }
        for(int i = 0; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }
            if(!used[i]) {
                used[i] = true;
                item.add(nums[i]);
                generate(res, item, nums, used);
                used[i] = false;
                item.remove(item.size() - 1);
            }
        }
    }

O(n!)

results matching ""

    No results matching ""