【VIP】【leetcode题解】【回溯】【97.5】【M】Subsets

175 篇文章 0 订阅
157 篇文章 0 订阅

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

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


Subscribe to see which companies asked this question


两种方法,一个是位操作,一个是回溯。


class Solution(object):

    def backtrack(self,nums,temp,start,t_len,res):
        if len(temp) == t_len:
            t = temp[:]#不这么写,它添加的东西会不对
            res.append(t)
            #print res,'    ',t
        else:
            for i in range(start,len(nums)):#最开始这个写成了t_len,错
                #print t_len,i,temp
                temp.append(nums[i])
                self.backtrack(nums,temp,i+1,t_len,res)
                temp.pop(-1)

    def subsets(self, nums):

        l = len(nums)
        res = []
        nums.sort()

        for i in range(0,l+1):
            temp = []
            #print '-----------'
            self.backtrack(nums,temp,0,i,res)

        return res

        '''
        l = len(nums)

        n = 1 << l
        res = []
        for i in range(0,n):
            j = 0
            temp = []
            while i > 0:
                if i & 1 :
                    temp.append( nums[j])
                i >>= 1

                j += 1
            temp.sort()
            res.append(temp)
        return res


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值