Subsets II

Leetcode 90.

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
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<Integer> list = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
Arrays.sort(nums);
for(int i = 0; i <= nums.length;i++){
backtricking(nums,list,ans,0,i,visited);
}

return ans;
}
public void backtricking(int[] nums,List<Integer> list, List<List<Integer>> ans,int start,int depth,boolean[] visited){
//recursion stop condition
if(list.size() == depth){
//collect the results
//shallow clone
ans.add(new ArrayList<>(list));
return;
}

//for loop for this layer
for(int i = start; i < nums.length;i++){
//process the nodes
if(i != 0 && nums[i] == nums[i-1] && !visited[i - 1])
continue;
if(visited[i])
continue;
visited[i] = true;
list.add(nums[i]);
//recursion
backtricking(nums,list,ans,i,depth,visited);
//undo the previous operations
visited[i] = false;
list.remove(list.size() - 1);
}

}
}