• [LeetCode] 90. Subsets II


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

    子集II。

    题意跟78题几乎一样,唯一多一个条件是input里面有重复元素,但是请不要重复输出相同的子集。思路还是回溯,套用78题的模板。注意这个题是需要对input排序的,在helper函数中,需要skip相同元素。

    时间O(nlogn) - 因为sort了input + O(2^n) = O(2^n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public List<List<Integer>> subsetsWithDup(int[] nums) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         // corner case
     5         if (nums == null || nums.length == 0) {
     6             return res;
     7         }
     8         Arrays.sort(nums);
     9         helper(res, new ArrayList<>(), nums, 0);
    10         return res;
    11     }
    12 
    13     private void helper(List<List<Integer>> res, List<Integer> list, int[] nums, int start) {
    14         res.add(new ArrayList<>(list));
    15         for (int i = start; i < nums.length; i++) {
    16             if (i != start && nums[i] == nums[i - 1])
    17                 continue;
    18             list.add(nums[i]);
    19             helper(res, list, nums, i + 1);
    20             list.remove(list.size() - 1);
    21         }
    22     }
    23 }

    LeetCode 题目总结

  • 相关阅读:
    数据库事务的四大特性以及事务的隔离级别
    informer使用示例
    Linux内存、Swap、Cache、Buffer详细解析
    浏览器访问百度的整个过程
    安装zookeeper
    配置java环境
    promethues开发
    go mod常用操作说明
    redis使用基础
    channel的声明和使用
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12710043.html
Copyright © 2020-2023  润新知