LeetCode47. 全排列 II

这篇博客探讨了全排列问题中处理重复数字的两种方法:使用Set去重和利用used数组去重。作者详细解释了每种方法的思路,并提供了相应的Java代码实现。在Set去重的方法中,通过HashSet存储结果,避免重复;而在used数组去重的方法中,通过对数组排序和used数组的状态来避免重复的排列。这两种方法都有效地解决了全排列问题中的重复问题。
摘要由CSDN通过智能技术生成

思路

这个题和上一题的全排列不同的地方是有重复的数字。需要去重,这里去重有两种方法:一个是用set去重,一个将数组排序然后用used数组去重。

重点说下用used数组去重:

 

因为是排列问题,所以就要用used数组记录遍历的元素,而去重刚好也要记录遍历的元素,所以就二者合二为一了。

首先对数组进行排序,当一个元素没有被使用的时候usede是false,被使用过后就是true,所以当nums[i-1] == nums[i] && used[i-1]==false时,表明该元素在水平方向上已经使用过了。所以水平方向后面的元素不在使用,但是垂直方向可以使用。

代码

方法一:set去重

class Solution {
    Set<List<Integer>> res = new HashSet<>();
    List<Integer> path = new ArrayList<>();
    int[] usedNums = new int[31];
    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        fun(nums,used);
        return new ArrayList(res);
    }
    public void fun(int[] nums,boolean[] used){
        if(nums.length == path.size()){
            res.add(new ArrayList(path));
            return;
        }
        usedNums = new int[31];
        for(int i = 0;i<nums.length;i++){
            if(used[i] == true){
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            fun(nums,used);
            path.remove(path.size()-1);
            used[i] = false;
        }
    }
}

方法二:used数组去重

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        fun(nums,used);
        return res;
    }
    public void fun(int[] nums,boolean[] used){
        if(nums.length == path.size()){
            res.add(new ArrayList(path));
            return;
        }
        for(int i = 0;i<nums.length;i++){
            if(i>0 && nums[i-1] == nums[i] && used[i-1] == false){
                continue;
            }
            if(used[i] == false){
                path.add(nums[i]);
                used[i] = true;
                fun(nums,used);
                path.remove(path.size()-1);
                used[i] = false;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想进阿里的小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值