就是组合算法,详细看我的另一篇非递归组合算法
class Solution(object):
def combination(self,num_list, n):
length = len(num_list)
init_list = [1] * n + [0] * (length - n)
start = True
result = []
while start:
start = False
judge = True
if init_list[0] == 1:
count=1
tmp = [num_list[0]]
else:
count=0
tmp = []
for i in xrange(1, length):
if init_list[i] == 1:
count+=1
tmp.append(num_list[i])
if judge and init_list[i - 1] == 1 and init_list[i] == 0:
start = True
count-=1
init_list[i], init_list[i - 1] = init_list[i - 1], init_list[i]
for j in xrange(i-1):
if j<count:
init_list[j]=1
else:
init_list[j]=0
judge = False
result.append(tmp)
return result
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
for i in xrange(len(nums)+1):
result+=self.combination(nums,i)
return result