forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPowerset.java
More file actions
46 lines (38 loc) · 1.08 KB
/
Powerset.java
File metadata and controls
46 lines (38 loc) · 1.08 KB
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
package algoexpert.medium;
/*
PROBLEM:
Return power set of given array
Example:
[1,2,3] -> [ [], [1], [2], [3], [1,2], [2,3], [1,3], [1,2,3]]
Solution:
1. time : O(n * 2^n) | Space : O(2^n)
*/
import java.util.ArrayList;
public class Powerset
{
public static void test()
{
ArrayList<Integer> array = new ArrayList<Integer>();
array.add(1);
array.add(2);
array.add(3);
System.out.println(powerset(array) );
}
// time : O (n * 2^n) | space : O (n * 2^n)
public static ArrayList<ArrayList<Integer>> powerset ( ArrayList<Integer> array)
{
ArrayList<ArrayList<Integer>> solution = new ArrayList<ArrayList<Integer>>();
solution.add(new ArrayList<Integer>());
for (Integer elem : array)
{
int length = solution.size();
for (int i = 0; i < length; ++i)
{
ArrayList<Integer> current = new ArrayList<Integer> (solution.get(i));
current.add(elem);
solution.add(current);
}
}
return solution;
}
}