Leetcode 子集 II

本文介绍了如何运用深度优先搜索(DFS)解决LeetCode第90题——子集II。通过排序数组并避免重复子集,实现所有可能子集的生成。详细阐述了解题思路、时间及空间复杂度,并提供了Python和PHP两种语言的代码实现。
摘要由CSDN通过智能技术生成
WechatIMG625.jpeg

题目描述

leetcode 第90题:子集 II
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

解题方法

DFS参照题解

  • 解题思路

获取整数数组nums的长度n
因为整数数组是无序的,需要先对整数数组排序
对整数数组进行DFS,起始索引index从0开始,初始子集path为空数组
如果当前子集不存在于解集res中,进行插入
[index,n)区间继续遍历整数数组
如果当前索引i大于起始索引,且nums[i]等于nums[i-1]跳过
然后进行下一次DFS,直到解集中包含所有情况的子集

  • 复杂度

时间复杂度:O(n2^n)
空间复杂度:O(n
2^n)

  • 代码实现

python3

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        def dfs(index,path):
            if path not in res:
                res.append(path)
            for i in range(index,n):
                if i>index and nums[i]==nums[i-1]:
                    continue
                dfs(i+1,path+[nums[i]])
        n = len(nums)
        nums.sort()
        res = []
        dfs(0,[])
        return res

php

class Solution {
    function subsetsWithDup($nums) {
        $this->nums = $nums;
        $this->n = count($nums);
        sort($this->nums);
        $this->res = [];
        $this->dfs(0,[]);
        return $this->res;
    }

    function dfs($index,$path){
        if(!in_array($path,$this->res)){
            array_push($this->res,$path);
        }
        for($i=$index;$i<$this->n;$i++){
            if($i>$index && $this->nums[$i]==$this->nums[$i-1]){
                continue;
            }
            $this->dfs($i+1,array_merge($path,[$this->nums[$i]]));
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值