-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubSet.java
56 lines (43 loc) · 1.44 KB
/
SubSet.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.vinay.practice.lc;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/subsets/description/
public class SubSet {
public static void main(String[] args) {
// TODO Auto-generated method stub
int nums[] = new int[] {1,2,3};
subsetArrayInt(nums);
}
// loop solution
public static List<List<Integer>> subsetArrayInt(int[] nums) {
List<List<Integer>> arr = new ArrayList<>();
arr.add(new ArrayList<>());
for (int j : nums) {
List<List<Integer>> temp = new ArrayList<>();
for (List<Integer> i : arr) {
List<Integer> subset = new ArrayList<>(i);
subset.add(j);
temp.add(subset);
}
arr.addAll(temp);
System.out.println(arr);
}
return arr;
}
// Backtracking solution
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ll= new ArrayList<>();
sub(nums,ll,new ArrayList<>(),0);
return ll;
}
public static void sub(int[] nums,List<List<Integer>> ll,List<Integer> result,int idx){
ll.add(new ArrayList<>(result));
for(int i=idx;i<nums.length;i++){
// adding element
result.add(nums[i]);
sub(nums,ll,result,i+1); //i+1 for unique elements
// removing element (backtracking)
result.remove(result.size()-1);
}
}
}