• LeetCode 90. Subsets II


    LeetCode 90. Subsets II (子集 II)

    题目

    链接

    https://leetcode.cn/problems/subsets-ii/

    问题描述

    给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。

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

    示例

    输入:nums = [1,2,2]
    输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]

    提示

    1 <= nums.length <= 10
    -10 <= nums[i] <= 10

    思路

    这题和78子集是同一思路,只需要打一个补丁即可。

    首先先对数组进行排序,确保相同的数字会在一起,然后在遍历时进行处理,如果该元素和前一元素相同,那么在该次遍历就不用考虑。

    复杂度分析

    时间复杂度 O(n2)
    空间复杂度 O(n)
    

    代码

    Java

        LinkedList<Integer> path = new LinkedList<>();
        List<List<Integer>> ans = new ArrayList<>();
    
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            Arrays.sort(nums);
            trace(nums, 0);
            return ans;
        }
    
        public void trace(int[] nums, int index) {
            ans.add(new ArrayList<>(path));
            for (int i = index; i < nums.length; i++) {
                if (i > index && nums[i] == nums[i - 1]) {
                    continue;
                }
                path.add(nums[i]);
                trace(nums, i + 1);
                path.removeLast();
            }
        }
    
  • 相关阅读:
    MySQL主从复制
    MySQL索引
    MySQL视图(view)
    MySQL表类型和存储引擎
    MySQL事务(三)
    MySQL事务(二)
    MySQL事务(一)
    MySQL事件调度器
    协同过滤推荐算法
    SVD奇异值分解
  • 原文地址:https://www.cnblogs.com/blogxjc/p/16375472.html
Copyright © 2020-2023  润新知