-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathAllSubsetsUsingBitwise.java
92 lines (87 loc) · 1.51 KB
/
AllSubsetsUsingBitwise.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.java.strings;
import java.util.Scanner;
/*
* Find All Subsets using Bitwise Approach
* ---------------------------------------
*
* The subset of a string is the character
* or the group of characters that are present
* inside the string.
* All the possible subsets for a string
* will be 2^n (n is the no of characters).
*
* say Given String is "abc"
* { }
* { a }
* { b }
* { a b }
* { c }
* { a c }
* { b c }
* { a b c }
*
* Using Bitwise Approach
* every characters will be denoted by a bit
*
* cba
* 000 { }
* 001 { a }
* 010 { b }
* 011 { a b }
* 100 { c }
* 101 { a c }
* 110 { b c }
* 111 { a b c }
*
*/
public class AllSubsetsUsingBitwise {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any String : ");
String str = scanner.nextLine().trim();
printAllSubsets(str);
scanner.close();
}
//using bitwise approach
public static void printAllSubsets(String str) {
char set[] = str.toCharArray();
int n = set.length;
for (int i = 0; i < (1 << n); i++) {
System.out.print("{ ");
for (int j = 0; j < n; j++){
if ((i & (1 << j)) > 0)
System.out.print(set[j] + " ");
}
System.out.println("}");
}
}
}
/*
OUTPUT
Enter any String : abcd
{ }
{ a }
{ b }
{ a b }
{ c }
{ a c }
{ b c }
{ a b c }
{ d }
{ a d }
{ b d }
{ a b d }
{ c d }
{ a c d }
{ b c d }
{ a b c d }
Enter any String : one
{ }
{ o }
{ n }
{ o n }
{ e }
{ o e }
{ n e }
{ o n e }
*/