leetcode-47 Permutations II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38340127/article/details/89876700

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

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

直接按照46的方法二,字典排序 即可简单的求出结果:(字典排序方法参考题目31 NextPermutation)

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        List<Integer> begin = new ArrayList<>();
        for(int tmp:nums) {
            begin.add(tmp);
        }
        res.add(begin);
        
        
        
        addNext(res,nums);
        return res;
    }
    
    public void addNext(List<List<Integer>> res,int[] nums) {
        for (int index = nums.length - 2; index >= 0; index--) {
            for (int j = nums.length - 1; j > index; j--) {
                if (nums[j] > nums[index]) {
                    int temp = nums[j];
                    nums[j] = nums[index];
                    nums[index] = temp;
                    Arrays.sort(nums, index + 1, nums.length);
                    List<Integer> begin = new ArrayList<>();
                    for(int tmp:nums) {
                        begin.add(tmp);
                    }
                    res.add(begin);
                    addNext(res,nums);
                }
            }
        }
        
    }

猜你喜欢

转载自blog.csdn.net/qq_38340127/article/details/89876700