您的位置:首页 > 其它

Subsets

2015-01-08 12:51 239 查看
Given a set of distinct integers, S, return all possible subsets.

Note:

Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.

For example,

If S =
[1,2,3]
, a solution is:

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


Analysis:

There are two ways to think about it.

first: each element in S could be selected or not selected. we can use recursion.

second: for n.th element, the number of subsets is twice as large as that of subsets created by first n-1 elements. we can use recursion or iteration.

class Solution:
    # @param S, a list of integer
    # @return a list of lists of integer
    
    ## wu ##  recursive
    def subsets(self, S):
        if len(S)==0:
            return [[]]
        
        res = [[]]
        S = sorted(S)
        for elem in S:
            newres = []
            for elemres in res:
                new = elemres[:]
                new.append(elem)
                newres.append(new)
            res = res + newresHTere
        
        return res


Summary:

get the deeper understanding of recursion and iteration. For iteration, it is usual that there is a for loop in it. For recursion, we only have one function to enter the process and another function will call itself many times. Sometimes, there is a internal
variable pass through all iterative funcitons.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: