LeetCode 47. 全排列 II

全排列I基础上判断集合中是否存在重复,添加不重复元素即可。

方法一: 利用Set,简单效率低

public static List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        Set<List<Integer>> ll = new HashSet<>();
        boolean[] v = new boolean[nums.length];
        dfs(ll,new ArrayList<Integer>(),nums,v);
        List<List<Integer>> r = new ArrayList<>();
        Iterator it = ll.iterator();
        while (it.hasNext()){
            r.add((List<Integer>)it.next());
        }
        return r;
    }
    public static void dfs(Set<List<Integer>> ll,List<Integer> l,int[] nums,boolean[] v){
        if(l.size() == nums.length){
            ll.add(new ArrayList<>(l));
        }
        for(int i=0;i<nums.length;i++){
            if(v[i])continue;
            l.add(nums[i]);
            v[i]=true;
            dfs(ll,l,nums,v);
            l.remove(l.size() - 1);
            v[i] = false;
        }
    }

方法二:利用经典去重

当本次nums[i]已经被选用时,跳过本次循环。

当本次nums[i]和nums[i-1]重复,且v [i-1]已经被使用了,跳过本次循环。

public static List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ll = new ArrayList<>();
        boolean[] v = new boolean[nums.length];
        dfs(ll,new ArrayList<Integer>(),nums,v);
        return ll;
    }

    private static void dfs(List<List<Integer>> ll, ArrayList<Integer> l, int[] nums, boolean[] v) {
        if(l.size()== nums.length){
            ll.add(new ArrayList<>(l));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(v[i])continue;
            if(i>0 && nums[i-1]==nums[i] && v[i-1])continue;
            l.add(nums[i]);
            v[i]=true;
            dfs(ll,l,nums,v);
            l.remove(l.size()-1);
            v[i]=false;
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值