90. Subsets II

栏目: Java · 发布时间: 6年前

内容简介: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:

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

难度:medium

题目:给定一可能含有重复元素的集合,返回所有可能的子集合。

注意:答案不能含有重复子集。

思路:递归,排序去重

Runtime: 3 ms, faster than 45.31% of Java online submissions for Subsets II.

Memory Usage: 35.7 MB, less than 0.97% of Java online submissions for Subsets II.

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            subsetsWithDup(nums, 0, i + 1, new Stack<Integer>(), result);
        }
        result.add(new ArrayList<>());
        return result;
    }
    
    public void subsetsWithDup(int[] nums, int idx, int count, Stack<Integer> stack, List<List<Integer>> result) {
        if (count <= 0) {
            result.add(new ArrayList<>(stack));
            return;
        }
        
        for (int i = idx; i < nums.length - count + 1; i++) {
            if (i == idx || nums[i - 1] != nums[i]) {
                stack.push(nums[i]);
                subsetsWithDup(nums, i + 1, count - 1, stack, result);
                stack.pop();
            }
        }
    }
}

以上所述就是小编给大家介绍的《90. Subsets II》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计数组合学(第一卷)

计数组合学(第一卷)

斯坦利 / 付梅、侯庆虎、辛国策 / 高等教育 / 2009-6 / 42.00元

《计数组合学(第1卷)》是两卷本计数组合学基础导论中的第一卷,适用于研究生和数学研究人员。《计数组合学(第1卷)》主要介绍生成函数的理论及其应用,生成函数是计数组合学中的基本工具。《计数组合学(第1卷)》共分为四章,分别介绍了计数(适合高年级的本科生),筛法(包括容斥原理),偏序集以及有理生成函数。《计数组合学(第1卷)》提供了大量的习题,并几乎都给出了解答,它们不仅是对《计数组合学(第1卷)》正......一起来看看 《计数组合学(第一卷)》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具