子集-力扣解题

给你一个整数数组 nums ,数组中的元素互不相同。返回该数组所有可能的子集(幂集)。

解集不能包含重复的子集。你可以按任意顺序返回解集。

提示

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • nums 中的所有元素 互不相同
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

输入:nums = [0]
输出:[[],[0]]
#解一
import copy
def subsets(lst: list) -> list:
    res = []
    res.append([])
    for i in range(len(lst)):
        # i = 1, 2, 3, 4
        r = copy.deepcopy(res)
        for j in range(len(res)):
            r[j].append(lst[i])

        for k in r:
            res.append(k)
    return res
#解二
import copy
def subsets(lst: list) -> list:
    res = []
    res.append([])

    for i in range(1, len(lst)+1):
        # i = 长度
        dfs(lst, res, i, 0, [])
    return res

def dfs(lst:list, res:list, length:int, index:int, subset:list):
    if len(subset) == length:
        r = copy.deepcopy(subset)
        res.append(r)
        return

    for i in range(index, len(lst)):
        subset.append(lst[i])
        dfs(lst, res, length, i+1, subset)
        subset.pop()
#解三
import copy
def subsets(lst: list) -> list:
    res = []
    dfs(lst, res, 0, [])
    return res

def dfs(lst:list, res:list, index:int, subset:list):
    res.append(copy.deepcopy(subset))
    if len(lst) == index:
        return

    for i in range(index, len(lst)):
        subset.append(lst[i])
        dfs(lst, res, i+1, subset)
        subset.pop()
#解四
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        length = len(nums)
        b = []

        for i in range(0, int(math.pow(2,length))):
            c = bin(i)[2:]
            if len(c) == length:
                b.append(c)
                continue
            b.append('{:0>{}}'.format(c, length))

        c = []
        for i in b:
            d = []
            for j in range(len(i)):
                if i[j] == '1':
                    d.append(nums[j])
            c.append(d)
        return c
posted @ 2021-02-02 22:39  EdenWu  阅读(106)  评论(0编辑  收藏  举报