方法一:每一次遍历,都在前面已有的集合里,再加上一个元素。
代码一:
def subsets(nums):
result = [[]]
for num in nums:
for element in result[:]:
x=element[:]
x.append(num)
result.append(x)
return result
代码二:
def subsets_2(nums):
res = [[]]
for num in nums:
res += [ i + [num] for i in res]
return res
二进制法
def PowerSetsBinary(nums):
N = len(nums)
res = []
for i in range(2**N):
combo = []
for j in range(N):
if(i >> j ) % 2 == 1:
combo.append(nums[j])
res.append(combo)
return res
原文:https://www.cnblogs.com/double-li912/p/13375718.html