首页 > 代码库 > [leetcode]Subsets @ Python

[leetcode]Subsets @ Python

原题地址:https://oj.leetcode.com/problems/subsets/

题意:枚举所有子集。

解题思路:碰到这种问题,一律dfs。

代码:

class Solution:
    # @param S, a list of integer
    # @return a list of lists of integer
    
    def subsets(self, S):
        def dfs(depth, start, valuelist):
            res.append(valuelist)
            if depth == len(S): return
            for i in range(start, len(S)):
                dfs(depth+1, i+1, valuelist+[S[i]])
        S.sort()
        res = []
        dfs(0, 0, [])
        return res