Subsets

Leetcode 78.

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
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<Integer> list = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
ans.add(list);
boolean[] visited = new boolean[nums.length];
for(int i = 1; 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 results
ans.add(new ArrayList<>(list));
return;
}

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

}
}