題目
給定一個含不同整數的集合,返回其所有的子集
(子集中的元素排列必須是非降序的,解集必須不包含重復的子集)
如果 S = [1,2,3],有如下的解:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解決subSets模板
先判斷輸入的list是否存在與長度是否大于0
使用一個subSetsHelper
params依次 是字符串本身,起始坐標,深度遍歷臨時存儲的temp_list ret是結果
https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73049
解決
class Solution:
"""
@param S: The set of numbers.
@return: A list of lists. See example.
"""
def subsets(self, S):
result = []
if(S is None or len(S) < 0):
return result
def subSetsHelper(nums,startIndex,temp_list,ret):
ret.append([]+temp_list)
for i in range(startIndex,len(nums)):
#先添加,再移除
temp_list.append(nums[i])
subSetsHelper(nums,i+1,temp_list,ret)
temp_list.pop()
S.sort()
subSetsHelper(S,0,[],result)
return result