-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsetsII.java
More file actions
28 lines (24 loc) · 760 Bytes
/
SubsetsII.java
File metadata and controls
28 lines (24 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// https://leetcode.com/problems/subsets-ii/
// #array #backtracking
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> subset = new LinkedList<>();
Arrays.sort(nums);
backtracking(0, nums, subset, result);
return result;
}
private void backtracking(
int count, int[] nums, LinkedList<Integer> subset, List<List<Integer>> result) {
if (!result.contains(subset)) { // slow
result.add(new ArrayList<Integer>(subset));
}
for (int i = count; i < nums.length; i++) {
// forward
subset.addLast(nums[i]);
backtracking(i + 1, nums, subset, result);
// backward
subset.removeLast();
}
}
}