美文网首页算法学习
算法题--寻找数组的所有子集

算法题--寻找数组的所有子集

作者: 岁月如歌2020 | 来源:发表于2020-04-21 18:06 被阅读0次
image.png

0. 链接

题目链接

1. 题目

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

2. 思路1:回溯法

  • 每个子集的元素数可以为[0, len(nums)]
  • 对于每个元素数, 就是一个组合选取问题
  • 组合选取问题采用回溯法, 在回溯的每一步:
    • 选择范围: [start, len(nums) - 1]
    • 选择元素
    • 更新startk
    • 撤销选择
    • 当k=0时, 代表捕获了一个合法子集

3. 代码

# coding:utf8
from typing import List


class Solution:
    def combine(self, combs: List[List[int]], comb: List[int], nums: List[int], start: int, k: int):
        if k == 0:
            combs.append(comb.copy())
        else:
            for i in range(start, len(nums)):
                comb.append(nums[i])
                self.combine(combs, comb, nums, i + 1, k - 1)
                comb.pop()

    def subsets(self, nums: List[int]) -> List[List[int]]:
        combs = list()
        comb = list()
        for i in range(len(nums) + 1):
            self.combine(combs, comb, nums, 0, i)
        return combs


def my_test(solution, nums):
    print('input={}, output={}'.format(nums, solution.subsets(nums)))


solution = Solution()
my_test(solution, [1, 3, 5])

输出结果

input=[1, 3, 5], output=[[], [1], [3], [5], [1, 3], [1, 5], [3, 5], [1, 3, 5]]

4. 结果

image.png

相关文章

  • 算法题--寻找数组的所有子集

    0. 链接 题目链接 1. 题目 Given a set of distinct integers, nums, ...

  • LeetCode刷题For Swift·78. 子集

    1、原题 给你一个整数数组 nums ,返回该数组所有可能的子集(幂集)。解集不能包含重复的子集。 示例 1: 示...

  • 算法题--列出集合的所有子集

    0. 链接 题目链接 1. 题目 Given a collection of integers that migh...

  • LeetCode-4 寻找两个有序数组的中位数

    题目:4. 寻找两个有序数组的中位数 难度:困难 分类:数组 解决方案:二分查找、分治算法 今天我们学习第4题寻找...

  • js获取数组的所有子集

    使用javascript获取一个数组的所有子集,比如:[1, 2, 3] 的所有子集是:[[], [1], [2]...

  • 【leetcode】子集

    【leetcode】子集 题目: 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说...

  • 求数组的所有子集

    序言 在项目中,有时候我们需要求一个数组的所有子集。例如一个数组有三个元素,[a,b,c],求该数组的所有子集。分...

  • LeetCode-078-子集

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

  • 回溯

    回朔算法是使用递归的方式,遍历所有的状态,一般借助数组等结构进行“剪枝”,较少遍历的次数。 解决的是 子集、组合、...

  • 非空子集

    请编写一个方法,返回某集合的所有非空子集。 给定一个int数组A和数组的大小int n,请返回A的所有非空子集。保...

网友评论

    本文标题:算法题--寻找数组的所有子集

    本文链接:https://www.haomeiwen.com/subject/soypihtx.html