LeetCode-90. Subsets II

本文介绍了一种在存在重复元素的情况下生成所有可能子集的方法,并确保最终结果中没有重复的子集。通过使用排序和哈希集的方式实现有效去重。

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

题目描述

Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.

解题思路

这道题是subsets的变种,目前集合中允许有重复的元素,而结果集中不允许有重复的子集合。我是利用一个set来存储已经存在的子集合,通过这种方式实现了去重。

代码

class Solution {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    Set<String> set = new HashSet<String>();
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        result.add(new ArrayList<Integer>());
        if(nums == null || nums.length == 0)
            return result;
        Arrays.sort(nums);
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        for(int i=1;i<=nums.length;i++){
            subsetCore(nums,0,i,tmp);
        }
        return result;
    }
    private void subsetCore(int[] nums,int position,int count,List<Integer> tmp){
        if(count == 0 ){
            if(set.add(tmp.toString())){
                result.add(new ArrayList<Integer>(tmp));
            }
            return;
        }
        if(nums.length-position < count){
            return;
        }
        for(int i=position;i+count-1<nums.length;i++){
            tmp.add(nums[i]);
            subsetCore(nums,i+1,count-1,tmp);
            tmp.remove(tmp.size()-1);
            subsetCore(nums,i+1,count,tmp);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值