算法学习

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

2020-04-25  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

2. 思路1:迭代法

3. 代码

# coding:utf8
from typing import List
from collections import defaultdict


class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        # 先统计每个元素的出现次数
        num_dict = defaultdict(int)
        for num in nums:
            num_dict[num] += 1

        # 迭代的收集结果列表
        rtn_list = [[]]
        for num, count in num_dict.items():
            before_size = len(rtn_list)
            for i in range(before_size):
                for freq in range(1, count + 1):
                    rtn_list.append(rtn_list[i] + [num] * freq)

        return rtn_list


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


solution = Solution()
my_test(solution, [1, 2, 2])
my_test(solution, [0])

输出结果

input: nums=[1, 2, 2]; output: [[], [1], [2], [2, 2], [1, 2], [1, 2, 2]]
input: nums=[0]; output: [[], [0]]

4. 结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读