【LeetCode】 90. Subsets II 子集 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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],
[]
]
题目大意
给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
解题方法
和78题类似,只是有重复元素【LeetCode】 78. Subsets 子集(Medium)(JAVA)
1、对元素进行排序
2、遇到当前元素和前一元素相同,直接跳过
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
for (int i = 0; i <= nums.length; i++) {
sH(res, cur, nums, 0, i);
}
return res;
}
public void sH(List<List<Integer>> res, List<Integer> cur, int[] nums, int index, int k) {
if (k == 0) {
res.add(new ArrayList<>(cur));
return;
}
if (nums.length - index < k) return;
for (int i = index; i < nums.length; i++) {
if (i > index && nums[i] == nums[i - 1]) continue;
cur.add(nums[i]);
sH(res, cur, nums, i + 1, k - 1);
cur.remove(cur.size() - 1);
}
}
}
执行用时 : 1 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 39.6 MB, 在所有 Java 提交中击败了 5.62% 的用户