90. 子集 II

文章介绍了如何使用Java编程语言解决LeetCode中的一个题目,即给定一个包含重复元素的整数数组,找到所有可能的无重复子集。通过深度优先搜索(DFS)算法实现,包括使用sorted数组和一个布尔数组`used`来避免重复子集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列

 

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 

使用used数组

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

    }
    public void dfs(int begin,int[] nums,boolean[] used, List<Integer> path,List<List<Integer>> res){
        res.add(new ArrayList<>(path));
        for(int i = begin;i < nums.length;i++){
            //!used[i-1]代表回溯之前访问过,回溯以后重新置为false
            if(i > 0 && !used[i-1] && nums[i] == nums[i-1]){
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            dfs(i+1,nums,used,path,res);
            path.remove(path.size()-1);
            used[i] = false;
        }
    }
}

本题也可以不使用used数组来去重,因为递归的时候下一个startIndex是i+1而不是0。

如果要是全排列的话,每次要从0开始遍历,为了跳过已入栈的元素,需要使用used。

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length == 0){
            return res;
        }
        List<Integer> path = new ArrayList<>();
        Arrays.sort(nums);
        dfs(0,nums,path,res);
        return res;

    }
    public void dfs(int begin,int[] nums,List<Integer> path,List<List<Integer>> res){
        res.add(new ArrayList<>(path));
        for(int i = begin;i < nums.length;i++){
           
            if(i > begin && nums[i] == nums[i-1]){
                continue;
            }
            path.add(nums[i]);
            dfs(i+1,nums,path,res);
            path.remove(path.size()-1);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值