90 Subsets II

90. Subsets II

1. Question

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.
For example, Ifnums=[1,2,2], a solution is:
1
[
2
[2],
3
[1],
4
[1,2,2],
5
[2,2],
6
[1,2],
7
[]
8
]
Copied!

2. Implementation

(1) Backtracking
1
class Solution {
2
public List<List<Integer>> subsetsWithDup(int[] nums) {
3
List<List<Integer>> res = new ArrayList<>();
4
List<Integer> subset = new ArrayList<>();
5
Arrays.sort(nums);
6
getSubsets(nums, 0, subset, res);
7
return res;
8
}
9
10
public void getSubsets(int[] nums, int start, List<Integer> subset, List<List<Integer>> res) {
11
res.add(new ArrayList<>(subset));
12
13
for (int i = start; i < nums.length; i++) {
14
if (i > start && nums[i - 1] == nums[i]) {
15
continue;
16
}
17
subset.add(nums[i]);
18
getSubsets(nums, i + 1, subset, res);
19
subset.remove(subset.size() - 1);
20
}
21
}
22
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)