【重点】【DFS】90.子集II

文章介绍了如何使用深度优先搜索(DFS)算法解决Java编程中的经典问题——给定一个整数数组,找出所有可能的子集,包括重复元素。通过递归实现并利用排序优化处理相等元素

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

题目
此题是元素存在重复的情况,可对比不存在元素重复情况的题目:78.子集

法1:DFS

经典方法,必须掌握!!!

Python

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res, path = [], []
        self.dfs(nums, 0, res, path)

        return res
    
    def dfs(self, nums, start, res, path):
        if start == len(nums):
            res.append(path.copy())
            return

        path.append(nums[start]) # 选择nums[start]
        self.dfs(nums, start+1, res, path)
        path.pop()
        while start + 1 < len(nums) and nums[start+1] == nums[start]:
            start += 1
        self.dfs(nums, start+1, res, path)

Java

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

        return res;
    }

    public void dfs(int[] nums, int startIndex, List<List<Integer>> res, List<Integer> tmp) {
        if (startIndex == nums.length) {
            res.add(new ArrayList<>(tmp));
            return;
        }

        tmp.add(nums[startIndex]); // 选择startIndex
        dfs(nums, startIndex + 1, res, tmp);
        tmp.remove(tmp.size() - 1); // 不选startIndex
        while (startIndex + 1 < nums.length && nums[startIndex + 1] == nums[startIndex]) { // 如果去掉这个条件,则可解决【78.子集】
            ++startIndex;
        }
        dfs(nums, startIndex + 1, res, tmp);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值