-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpowerset
More file actions
77 lines (67 loc) · 1.2 KB
/
powerset
File metadata and controls
77 lines (67 loc) · 1.2 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
The powerset of any set S is the set of all subsets of S,
including the empty set and S itself.
To print all subsets, I used recursion and Stack.
Because there are two cases for each element (included or not),
the total subsets is 2^the number of elements,
we can solve this using recursion and Stack.
*/
import java.util.*;
public class Solution {
public static int count = 0;
public static int[] a = {1,2,3,4,5};
public static Stack<Integer> st = new Stack<>();
public static void powerset(int i) {
if (i==a.length) {
count++;
System.out.println(st);
return;
}
else {
st.push(a[i]); //the case of including this element
powerset(i+1);
st.pop(); //the case of not including this element
powerset(i+1);
}
}
public static void main(String[] args) {
powerset(0);
System.out.println("\n" + "The number of subsets: " + count);
}
}
/*****
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3, 5]
[1, 2, 3]
[1, 2, 4, 5]
[1, 2, 4]
[1, 2, 5]
[1, 2]
[1, 3, 4, 5]
[1, 3, 4]
[1, 3, 5]
[1, 3]
[1, 4, 5]
[1, 4]
[1, 5]
[1]
[2, 3, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 3]
[2, 4, 5]
[2, 4]
[2, 5]
[2]
[3, 4, 5]
[3, 4]
[3, 5]
[3]
[4, 5]
[4]
[5]
[]
The number of subsets: 32
*****/