一、要求

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()

 测试情况如下:LeetCode刷题4——子集

 

 

 

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

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

 

相关文章:

  • 2022-12-23
  • 2018-04-30
  • 2021-12-25
  • 2021-10-27
  • 2021-06-24
  • 2022-02-01
猜你喜欢
  • 2021-11-03
  • 2021-12-03
  • 2021-08-19
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2022-01-10
相关资源
相似解决方案