Subsets

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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值