当前位置:网站首页>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
边栏推荐
- 统计遗传学:第一章,基因组基础概念
- loggie 编码以及换行符测试
- PC qq Hall upload Update Modifying versioninfo
- 4. N queen problem
- What should I do from member labels to portraits?
- Redis的最佳实践?看完不心动,算我输!!
- SolidWorks rendering tips how not to display edges -- display style settings
- Laravel admin obtains non auto increment ID and submits hidden forms
- Apiccloud implements the document download and preview functions
- Basic use of express in nodejs
猜你喜欢

Black squares in word

【毕业季·进击的技术er】忆毕业一年有感
![[graduation season · advanced technology Er] I remember the year after graduation](/img/e7/8e1dafa561217b77a3e3992977a8ec.png)
[graduation season · advanced technology Er] I remember the year after graduation

HUST网络攻防实践|6_物联网设备固件安全实验|实验二 基于 MPU 的物联网设备攻击缓解技术

2、 MySQL Foundation
![Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding](/img/58/2a56c5c9165295c830082f8b05dd98.png)
Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding

国际美妆业巨头押注中国

【概率论】条件概率、贝叶斯公式、相关系数、中心极限定理、参数估计、假设检验

Statistical genetics: Chapter 1, basic concepts of genome

Machine Learning Clustering - Experimental Report
随机推荐
18: Chapter 3: development of pass service: 1: SMS login & registration process, introduction; (SMS verification code is used here)
女性科学家的流失
MQTT断开重连
修改calico网络模式为host-gw
国际美妆业巨头押注中国
DD command tests the read and write speed of Huawei Kunpeng & Hongshan solid state storage disk
The most complete kubernetes core command of the latest version so far
Laravel writes native SQL statements
Five trends of member marketing of consumer goods enterprises in the future
18:第三章:开发通行证服务:1:短信登录&注册流程,简介;(这儿使用短信验证码)
11、 Box styles and user interface
2、 MySQL Foundation
FasterRCNN
Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open a mobile account?
房租是由什么决定的
这两天搭建环境遇到的几个问题
十大券商有哪些?手机开户安全么?
科技兴关,荣联与天津海关共建基因组数据库及分析平台
Ctfshow web getting started command execution web75-77
VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」