[leetcode]90. Subsets II数组子集(有重)

时间:2022-03-10 13:16:56

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.

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

题意:

是的[leetcode]78. Subsets数组子集 follow up

这题强调给定数组可以有重复元素

思路:

需要先对给定数组排序,以便去重

代码:

 class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums == null || nums.length ==0 )return result;
Arrays.sort(nums);
List<Integer> path = new ArrayList<>();
dfs(0, nums, path, result);
return result;
} private void dfs(int index, int[] nums, List<Integer> path, List<List<Integer>> result){
result.add(new ArrayList<>(path));
for(int i = index; i < nums.length; i++){
if( i != index && nums[i] == nums[i-1] ) continue;
path.add(nums[i]);
dfs(i + 1, nums, path, result);
path.remove(path.size() - 1);
}
}
}