'Print All the subset from a string
I want to print all the Ppower set of a string let say the string INPUT - "ab" OUTPUT - " ", "a", "b", "ab"
#include <bits/stdc++.h>
using namespace std;
void solve(string ip, string op)
{
if (ip.length() == 0)
{
cout << op;
return;
}
string op1 = op;
string op2 = op;
op2.push_back(ip[0]);
ip.erase(ip.begin() + 0);
solve(ip, op1);
solve(ip, op2);
}
int main()
{
string ip = "ab";
string op = "";
solve(ip, op);
// cout << "Hello";
return 0;
}
In this code only three subset of this string is coming "a", "b" and "ab" not " ". Dont know where my code is stuck. Thank you
Solution 1:[1]
Of course you can't get ' ', because your string doesn't contain a space. So therefore it is an exclusion, and when your op is empty then you should print the space ' ', like this see the corrected code. I checked only that part you were wanting for.
#include <bits/stdc++.h>
using namespace std;
void solve(string ip, string op)
{
if (ip.length() == 0)
{
if (op=="") cout << " ";
else cout << op;
return;
}
string op1 = op;
string op2 = op;
op2.push_back(ip[0]);
ip.erase(ip.begin() + 0);
solve(ip, op1);
solve(ip, op2);
}
int main()
{
string ip = "ab";
string op = "";
solve(ip, op);
// cout << "Hello";
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aibek Bakirov |
