[LeetCode] 90. Subsets II

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

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

子集II。

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/subsets-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 题目总结

posted @ 2020-04-16 03:03  CNoodle  阅读(418)  评论(0编辑  收藏  举报