LeetCode 90. Subsets II

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

v2-8d455f0f21c5e94faf01c52439b5b54d_1440w.jpg

Description



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],
  []
]


描述



  • 此题是78题的递进题.
  • 此题求给定数组的所有可能的子集,与78题不同,此题给定的数据可能有重复.
  • 我们首先对给定的数组排序,然后如果当前元素与前一个元素相同,我们跳过进行下一步.
  • 基本思路同78题完全一致.


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2018-12-25 21:24:06
# @Last Modified by:   何睿
# @Last Modified time: 2018-12-25 21:41:42
import copy
class Solution:
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = [[]]
        nums = sorted(nums)
        self.recursion(res, [], nums, 0, len(nums))
        return res
    def recursion(self, res, path, nums, start, end):
        if start == end:
            return
        for i in range(start, end):
            if i != start and nums[i] == nums[i-1]:
                continue
            else:
                path.append(nums[i])
                res.append(copy.deepcopy(path))
                self.recursion(res, path, nums, i+1, end)
                path.pop()
if __name__ == "__main__":
    so = Solution()
    res = so.subsetsWithDup([1, 1, 6, 2])
    print(res)


源代码文件在这里.


目录
相关文章
|
Python
[LeetCode] Subsets
Recursive (Backtracking) This is a typical problem that can be tackled by backtracking. Since backtracking has a more-or-less similar template, so I do not give explanations for this method.
993 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
591 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
298 6
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
634 2
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
575 4
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口