[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

 

posted @ 2014-05-28 15:54  南郭子綦  阅读(6072)  评论(2编辑  收藏  举报