当前位置:网站首页>Leetcode 78. 子集 and 90. 子集 II
Leetcode 78. 子集 and 90. 子集 II
2022-06-26 10:54:00 【von Libniz】
78. 子集
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
排列问题,一般都可以用深搜做,当然广搜也可以,这里给出三种解法。
深搜1
构建一棵二叉树,每层判断是否要放入nums[i],由根节点到叶子节点的路径构成一个子集。
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def dfs(path, depth):
if depth == len(nums):
res.append(path[:])
return
path.append(nums[depth])
dfs(path, depth + 1)
path.pop()
dfs(path, depth + 1)
res = []
dfs([], 0)
return res
深搜2
每层从剩下的可选数字中选择一个放入,从第0层往下,第i层代表含有i个元素的子集,所以每层要保存到答案中。为了避免重复,先对数组排序,只选择更大的元素放入(保证升序)。
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def dfs(path, index):
res.append(path[:])
for i in range(index, len(nums)):
path.append(nums[i])
dfs(path, i + 1)
path.pop()
res = []
nums.sort()
dfs([], 0)
return res
动态规划
由可选的数字各不相同,每加入一个数字,就将未加入前的子集的子集数量翻了个倍,因此可以采用dp递推,从遍历角度也像是BFS。
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for num in nums:
for i in range(len(res)):
res.append(res[i] + [num])
return res
90. 子集 II
相比子集1就多了一个条件,数组中存在重复元素,需要我们做到去重操作。同样给出dfs与dp两种解法。
dfs
同层的数字选择中,不应该出现重复元素。因此如果该层的数字选择与上次相同,就跳过。
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
def dfs(path, index):
res.append(path[:])
for i in range(index, len(nums)):
if i > index and nums[i - 1] == nums[i]:
continue
path.append(nums[i])
dfs(path, i + 1)
path.pop()
nums.sort()
res = []
dfs([], 0)
return res
dp
采用动态规划依旧要去重,通过排序将相同元素挨在一起,可以发现,如果这次要放入的元素与上次相同,只需要增加1/2的数量(否则出现重复),若上上次也是相同的数字,则增加1/3的子集数,如此类推。
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
res = [[]]
nums.sort()
count = 2
for i in range(len(nums)):
if i > 0 and nums[i - 1] == nums[i]:
for j in range(len(res) - len(res) // count, len(res)):
res.append(res[j] + [nums[i]])
count += 1
else:
for j in range(len(res)):
res.append(res[j] + [nums[i]])
count = 2
return res
也可以用new_subsets记录这次新增加的子集,下次遇到重复元素,只需在nwe_subsets的基础上做增加。
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
res = [[]]
nums.sort()
for i in range(len(nums)):
if i > 0 and nums[i - 1] == nums[i]:
new_subsets = [subset + [nums[i]] for subset in new_subsets]
else:
new_subsets = [subset + [nums[i]] for subset in res]
res += new_subsets
return res
边栏推荐
- loggie 编码以及换行符测试
- Flannel's host GW and calico
- Work report (3)
- PC QQ大廳 上傳更新 修改versionInfo
- Will updating a large amount of data in Oracle cause the undo space to explode
- Unity使用SteamVRPlugin时如何不让其他Camera位置和旋转收到SteamVRPlugin控制
- Build document editor based on slate
- 我想知道同花顺是炒股的么?手机开户安全么?
- Implementing MySQL master-slave replication in docker
- Laravel admin login add graphic verification code
猜你喜欢

Pratique de l'attaque et de la défense du réseau HUST | 6 Expérience de sécurité du microprogramme de l'équipement IOT | expérience 2 technologie d'atténuation des attaques de l'équipement IOT basée s

flannel的host-gw与calico

Excel operation of manual moving average method and exponential smoothing method for time series prediction
![[deep learning theory] (6) recurrent neural network RNN](/img/33/e270b08e7748a6e740eb618ed10c9a.gif)
[deep learning theory] (6) recurrent neural network RNN

sliding window

Machine learning linear regression - Experimental Report

(Typora图床)阿里云oss搭建图床+Picgo上传图片详细教程

APICloud 实现文档下载和预览功能

02 linked list of redis data structure

深度学习中的FLOPs和Params如何计算
随机推荐
APICloud 实现文档下载和预览功能
dd命令测试华为鲲鹏&宏衫固态存储磁盘读写速度
Nacos2.x.x start error creating bean with name 'grpcclusterserver';
【深度学习理论】(7) 长短时记忆网络 LSTM
flannel的host-gw与calico
Group by is used in laravel to group and query the quantity
【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构
动态规划解决股票问题(下)
统计遗传学:第二章,统计分析概念
中国十大证券app排名 开户安全吗
汇编语言(7)运算指令
即构「畅直播」上线!提供全链路升级的一站式直播服务
How to prevent weight loss under Gao Bingfa?
Compréhension approfondie de l'expérience de port série stm32 (registre) [Tutoriel de niveau nounou]
Statistical genetics: Chapter 1, basic concepts of genome
(typora picture bed) Alibaba cloud OSS building picture bed +picgo uploading picture detailed tutorial
Notice on printing and Distributing Measures for supporting strategic emerging industries and future industrial cluster development in Futian District, Shenzhen
请指教同花顺开户选选择哪家券商比较好?手机开户安全么?
18:第三章:开发通行证服务:1:短信登录&注册流程,简介;(这儿使用短信验证码)
Grain Mall - distributed Foundation