Skip to content

Commit 7391873

Browse files
committed
Power Set of a string
1 parent 45c9642 commit 7391873

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

14.Backtracking/PowerSet.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
// Find Power Set of a set of characters
4+
5+
void PrintSet(char result[], int len)
6+
{
7+
for (int i = 0; i < len; i++)
8+
printf("%c ", result[i]);
9+
10+
printf("\n");
11+
}
12+
13+
void Pset(char chs[], int count[], int pos, char result[], int depth, int cs)
14+
{
15+
PrintSet(result, depth);
16+
for (int i = pos; i < cs; i++)
17+
{
18+
if (count[i] != 0)
19+
{
20+
result[depth] = chs[i];
21+
count[i]--;
22+
Pset(chs, count, i, result, depth + 1, cs);
23+
count[i]++;
24+
}
25+
}
26+
}
27+
28+
void powerSet(char exp[])
29+
{
30+
map<char, int> cmap;
31+
int l = strlen(exp);
32+
33+
for (int i = 0; i < l; i++)
34+
{
35+
cmap.insert(pair<char, int>(exp[i], 0));
36+
map<char, int>::iterator it;
37+
it = cmap.find(exp[i]);
38+
++it->second;
39+
cmap.insert(pair<char, int>(exp[i], it->second));
40+
}
41+
42+
int cs = cmap.size();
43+
char chs[cs];
44+
int count[cs];
45+
46+
map<char, int> ::iterator it;
47+
int i = 0;
48+
for (it = cmap.begin(); it != cmap.end(); it++)
49+
{
50+
chs[i] = it->first;
51+
count[i] = it->second;
52+
i++;
53+
}
54+
55+
char result[cs];
56+
Pset(chs, count, 0, result, 0, cs);
57+
}
58+
59+
int main(int argc, char const *argv[])
60+
{
61+
char exp[1000];
62+
cout << "Enter an expression :";
63+
cin >> exp;
64+
65+
powerSet(exp);
66+
return 0;
67+
}

0 commit comments

Comments
 (0)