第一种思路:直接遍历,遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for i in range(len(nums)-1,-1,-1):
for subset in res[:]: res.append(subset+[nums[i]])
return res
第二种:位运算
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
results = []
subsets_size = 2 ** len(nums)
n = 0
while n < subsets_size:
subset = []
i = 0
bits = n
while bits > 0:
if bits & 1 == 1:
subset.append(nums[i])
i += 1
bits = bits >> 1
n += 1
results.append(subset)
return results
参考:https://leetcode-cn.com/problems/subsets/comments/