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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
dfs(list, new ArrayList<>(), nums, 0);
return list;
}

public void dfs(List<List<Integer>> list, List<Integer> arr, int[] nums, int start) {
list.add(new ArrayList<>(arr));
for (int i = start; i < nums.length; ++i) {
if (i > start && nums[i] == nums[i-1]) continue;
arr.add(nums[i]);
dfs(list, arr, nums, i + 1);
arr.remove(arr.size() - 1);
}
}
}
  • Arrays.sort是为了后面remove duplicates;
  • 因为后面dfs(..., i+1)仍然是i+1, 故ii-1比较,所以if去重条件是那样