90. 子集 II
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
class Solution {
private static void solve(List<List<Integer>> ret, LinkedList<Integer> path, List<Integer> numList, List<Integer> countList, int index) {
if (index == numList.size()) {
ret.add(new ArrayList<>(path));
return;
}
/**
* 不取这个数
*/
solve(ret, path, numList, countList, index + 1);
for (int i = 1; i <= countList.get(index); ++i) {
path.offerLast(numList.get(index));
solve(ret, path, numList, countList, index + 1);
}
for (int i = 1; i <= countList.get(index); ++i) {
path.pollLast();
}
}
public static List<List<Integer>> subsetsWithDup(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>(0);
}
Arrays.sort(nums);
List<Integer> numList = new ArrayList<>();
List<Integer> countList = new ArrayList<>();
int count = 1;
for (int i = 1; i < nums.length; ++i) {
if (nums[i] == nums[i - 1]) {
count++;
} else {
numList.add(nums[i - 1]);
countList.add(count);
count = 1;
}
}
numList.add(nums[nums.length - 1]);
countList.add(count);
List<List<Integer>> ret = new ArrayList<>();
solve(ret, new LinkedList<>(), numList, countList, 0);
return ret;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号