zoukankan      html  css  js  c++  java
  • [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 题目总结

  • 相关阅读:
    网络爬虫之第一章网络请求
    rabbitmq学习(一) —— 安装篇
    jenkins自动构建部署
    httpclient初步封装
    谈谈“拥抱变化”
    mongo对分组数据进行排序
    困兽
    go语言——goland中项目目录及编译说明
    最长回文子串
    java中关于锁知识的整理
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12710043.html
Copyright © 2011-2022 走看看