leetcode 每日一题 78. 子集

回溯法

思路:

参考77.组合

 

代码:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def process(path=[],begin=0):
            if len(path) == k:
                res.append(path[:])
                return
            for i in range(begin,len(nums)):
                path.append(nums[i])
                process(path,i+1)
                path.pop()
        res = []
        for k in range(len(nums)+1):
            process()
        return res

递归

思路:

先初始化一个子集为空数组的数组,遍历数组中的元素,每遍历一个元素,将此元素和数组中所有元素进行组合并添加进数组中。

例如:

1,2,3    nums = [ [] ]

1  :  [ [],[1] ]

2 :  [ [],[1],[2],[1,2] ]

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

代码:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        output = [[]]
        for num in nums:
            output += [curr + [num] for curr in output]
        return output

 二进制排序

思路:

数组元素的个数为n,则所有子集为n位二进制所能表示的所有可能,其中1表示元素在子集中,0表示不在子集中。

例如:

1,2,3

 

代码:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        output = []
        for i in range(2**n, 2**(n + 1)):
            bitmask = bin(i)[3:]
            output.append([nums[j] for j in range(n) if bitmask[j] == '1'])
        return output

 

posted @ 2020-06-13 15:23  nil_f  阅读(150)  评论(0编辑  收藏  举报