subSets

題目

給定一個含不同整數(shù)的集合,返回其所有的子集
(子集中的元素排列必須是非降序的,解集必須不包含重復(fù)的子集)
如果 S = [1,2,3],有如下的解:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

解決subSets模板

先判斷輸入的list是否存在與長度是否大于0
使用一個subSetsHelper
params依次 是字符串本身,起始坐標,深度遍歷臨時存儲的temp_list ret是結(jié)果
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容