forked from Abraarkhan/Java_Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubsetsofarray.java
37 lines (31 loc) · 1.08 KB
/
subsetsofarray.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
import java.util.*;
public class subsetsOfArray {
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int size = scn.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scn.nextInt();
}
int lim = (1 << size);// lim -> limit -> total number of subsets
// step 1 -> run loop from 0 -> limit
for (int i = 0; i < lim; i++) {
int dec = i;// dec -> decimal of 'i'
// find binary of the decimal and if rem is 0 then don't print, otherwise print
// element
// decimal to binary conversion
String str = "";
for (int j = 0; j < arr.length; j++) {
int rem = dec % 2;
dec = dec / 2;
if (rem == 0)
str = "- " + str;
else
str = arr[arr.length - 1 - j] + " " + str;
}
System.out.println(str);
}
scn.close();
}
}