-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path78.子集.py
More file actions
57 lines (56 loc) · 1.12 KB
/
78.子集.py
File metadata and controls
57 lines (56 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#
# @lc app=leetcode.cn id=78 lang=python
#
# [78] 子集
#
# https://leetcode-cn.com/problems/subsets/description/
#
# algorithms
# Medium (74.75%)
# Likes: 344
# Dislikes: 0
# Total Accepted: 37.3K
# Total Submissions: 49.8K
# Testcase Example: '[1,2,3]'
#
# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
#
# 说明:解集不能包含重复的子集。
#
# 示例:
#
# 输入: nums = [1,2,3]
# 输出:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
#
#第一种方法:递归
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res=[]
self.dfs(0,[],nums,res)
return res
def dfs(self,index,path,nums,res):
res.append(path)
print(path)
for i in range(index,len(nums)):
self.dfs(i+1,path+[nums[i]],nums,res)
#第二种:列表推导式
class Solution(object):
def subsets(self, nums):
res=[[]]
for num in nums:
res+=[[num]+item for item in res]
return res