LeetCode刷题4——子集

一、要求

 

 

 二、知识点

 1.回溯算法

    回溯算法相当于穷举法加剪枝,回溯算法总是和深度优先同时出现的,采用深度优先策略回溯到根,且根节点的所有子树都被搜索一遍才结束,并剪掉不符合要求的结果

 

三、解题思路

(1)采用回溯算法

对于列表数据先对每层进行一次循环(每层代表数组的数量,从0到len(num)),对每层满足要求的数组添加的res结果中

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        size =len(nums)
        res=[]
        for i in range(size+1):
            self.difs(nums,i,0,[],res)
        return res
    def difs(self,nums,depth,begin,path,res):
        if depth==len(path):
            res.append(path[:])
            return
        for i in range(begin,len(nums)):
            path.append(nums[i])
            self.difs(nums,depth,i+1,path,res)
            path.pop()

 测试情况如下:

 

 

 

(2)还有一种通过位运算的方式实现,例如长度是3的数组[1,2,3],[0 1 0] 表示输出[2],[1 1 0]表示输出[1,2]

通过这种方式,数组子集就替换成三个位置是否是0 1 的组合情况

 

posted @ 2019-11-14 21:54  bethansy  阅读(205)  评论(0编辑  收藏  举报