-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path12_generate_subsets_using_bitmasking.cpp
91 lines (69 loc) · 1.36 KB
/
12_generate_subsets_using_bitmasking.cpp
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
/*
Topic: Generate Subsets using Bitmasking
- Finding Subsequences/Subset of a Given String
(Remember Subsequences are continious whereas Subset are not continious)
Eg: Input : "abc"
Output: " ",a,ab,abc,ac,b,bc,c
*/
#include <iostream>
#include <cstring>
using namespace std;
// function to extract out character which maps with set-bit of number n
void filterChars(char c[], int n)
{
int idx=0;
while(n)
{
int last_bit = n&1;
if(last_bit == 1)
{
cout << c[idx];
}
idx++;
n = n>>1; // Discard the last bit
}
cout << endl;
}
void printSubsets(char c[])
{
int len = strlen(c);
// iterating over the list of numbers
for(int i=0; i < (1<<len); i++)
{
filterChars(c, i);
}
return;
}
// function to drive code
int main()
{
char c[100];
cout << "Enter character: ";
cin >> c;
cout << "Output: \n";
printSubsets(c);
return 0;
}
/*
OUTPUT:
Enter character: abc
Output:
a
b
ab
c
ac
bc
abc
Approach:
- Extracting out character which maps with set-bit from number 0 to 7
cba
0 : 000 | " "
1 : 001 | a
2 : 010 | b
3 : 011 | ab
4 : 100 | c
5 : 101 | ac
6 : 110 | bc
7 : 111 | abc
*/