当前位置:网站首页>Leetcode 78. Subset and 90 Subset II
Leetcode 78. Subset and 90 Subset II
2022-06-26 11:57:00 【von Libniz】
78. A subset of
Give you an array of integers nums , Elements in an array Different from each other . Returns all possible subsets of the array ( Power set ).
Solution set You can't Contains a subset of repetitions . You can press In any order Returns the solution set .
Example 1:
Input :nums = [1,2,3]
Output :[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input :nums = [0]
Output :[[],[0]]
The problem of permutation , Generally, you can use deep search to do , Of course, guangsearch is also OK , Here are three solutions .
Deep search 1
Build a binary tree , Each layer determines whether to put nums[i], The path from the root node to the leaf node constitutes a subset .
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
Deep search 2
Each layer selects one of the remaining optional numbers to put in , From 0 Layer down , The first i A layer represents a layer containing i A subset of elements , So each layer should be saved in the answer . To avoid repetition , Sort the array first , Only select larger elements to put into ( Ensure ascending order ).
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
Dynamic programming
The optional numbers are different , Every time you add a number , It doubles the number of subsets that have not been added to the previous subset , So you can use dp Recurrence , From the ergodic point of view, it also looks like 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. A subset of II
Comparison subset 1 Just one more condition , There are duplicate elements in the array , We need to do the de duplication operation . Also given dfs And dp Two kinds of solution .
dfs
In the digital selection of the same layer , There should be no duplicate elements . Therefore, if the digital selection of this layer is the same as last time , Just skip. .
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
Adopting dynamic planning still needs to be de emphasized , By sorting the same elements together , You can find , If the element to be placed this time is the same as the last time , Just add 1/2 The number of ( Otherwise, there will be repetition ), If it is the same number last time , Increase 1/3 Subsets of , And so on .
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
It can also be used. new_subsets Record the newly added subset , The next time you encounter a duplicate element , Just in nwe_subsets On the basis of .
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
边栏推荐
- 国际美妆业巨头押注中国
- Cross platform members get through the two channels of brand Ren Du
- 4. N queen problem
- 十大券商有哪些?手机开户安全么?
- Wangeditor uploading local video modification
- Machine learning SVM - Experimental Report
- 关于印发《深圳市福田区支持战略性新兴产业和未来产业集群发展若干措施》的通知
- 这两天搭建环境遇到的几个问题
- 统计遗传学:第二章,统计分析概念
- Change calico network mode to host GW
猜你喜欢
![In depth understanding of STM32 serial port experiment (register) [nanny level tutorial]](/img/b2/f09e220918a85b14a1993aa85f7720.png)
In depth understanding of STM32 serial port experiment (register) [nanny level tutorial]

. Net, the usage of log components NLog, seriallog, log4net

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

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

FasterRCNN

【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构

AD - 将修改后的 PCB 封装更新到当前 PCB 中

TCP interview

Matlab programming example: how to count the number of elements in a cell array
随机推荐
Build document editor based on slate
Matlab programming example: how to count the number of elements in a cell array
Five problems and solutions of member operation
11、 Box styles and user interface
房租是由什么决定的
Five trends of member management in 2022
Excel operation of manual moving average method and exponential smoothing method for time series prediction
Is it safe to open a securities account
FastRCNN
19: Chapter 3: develop pass service: 2: get through Alibaba cloud SMS service in the program; (it only connects with Alibaba cloud SMS server, and does not involve specific business development)
4. N queen problem
利用 Repository 中的方法解决实际问题
Omnichannel membership - tmall membership 2: frequently asked questions
Laravel admin hidden button, and set button display, default sequence, form form form non modifiable value
HUST网络攻防实践|6_物联网设备固件安全实验|实验二 基于 MPU 的物联网设备攻击缓解技术
我想知道,股票开户有哪些优惠活动?网上开户是否安全么?
Compréhension approfondie de l'expérience de port série stm32 (registre) [Tutoriel de niveau nounou]
科技兴关,荣联与天津海关共建基因组数据库及分析平台
ctfshow web入门 命令执行web75-77
汇编语言(7)运算指令