import datetime
def PowerSetsBinary(items):#1,二进制方法
N = len(items)
# generate all combination of N items
# enumerate the 2**N possible combinations
res=[]
for i in range(2 ** N):
combo = []
for j in range(N): # jth bit of Integer i
if (i >> j) % 2 == 1:
combo.append(items[j])
res.append(combo)
return res
def PowerSetsRecursive(items):#2,回归方法
"""Use recursive call to return all subsets of items, include empty set"""
if len(items) == 0:
# if the lsit is empty, return the empty list
return [[]]
subsets = []
first_elt = items[0] # first element
rest_list = items[1:]
# Strategy: Get all subsets of rest_list;
# for each of those subsets,a full subset list will contain both the original subset
# as well as a version of the subset that contains the first_elt(according to m
Python求一个集合的所有子集算法对比时间最短
最新推荐文章于 2022-03-11 09:37:49 发布