05 August 2008
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:
1
2
3
4
5
6
7
8
9
10
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
同上题的做法,多了一个判断待加入的元素是否是重复的判断。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null || nums.length == 0) {
return results;
}
Arrays.sort(nums);
backtracking(nums, results, new ArrayList<>(), 0);
return results;
}
private void backtracking(int[] nums, List<List<Integer>> results, List<Integer> oneResult, int index) {
results.add(new ArrayList<>(oneResult)); // 与78同,添加元素后到下一层递归时再加入到结果,因为要求空值,否则可以放在里面
for (int i = index; i < nums.length; i++) {
// 与78题唯一的区别,78题是用oneResult.contains()判断是否重复,这里从第二个点开始判断是否用了重复数字
if (i > index && nums[i] == nums[i - 1]) {
continue;
}
oneResult.add(nums[i]);
backtracking(nums, results, oneResult, i + 1);
oneResult.remove(oneResult.size() - 1);
}
}
}