Skip to content

Instantly share code, notes, and snippets.

@NicolaBernini
Created January 28, 2020 11:22
Show Gist options
  • Save NicolaBernini/1787c3ff4af6995c580b1c156ac25438 to your computer and use it in GitHub Desktop.
Save NicolaBernini/1787c3ff4af6995c580b1c156ac25438 to your computer and use it in GitHub Desktop.
Comnpute the power set of a set

Overview

Compute the Power Set of a Set in CPP

#include <iostream>
#include <vector>
#include <string>
using namespace std;
string to_str(const vector<int>& a)
{
string res="{";
for(const auto& e : a) res += (res!="{"?",":"") + to_string(e);
res += "}";
return res;
}
string to_str(const vector<vector<int>>& a)
{
string res;
for(const auto& e : a)
{
res += to_str(e) + "\n";
}
return res;
}
vector<vector<int>> power_set(vector<int> a)
{
if(a.size()==0) return {};
if(a.size()==1) return {{}, a};
if(a.size()>1)
{
vector<vector<int>> res;
res.reserve(2*a.size());
auto temp = power_set({a.begin(), a.end()-1});
res.insert(res.end(), temp.begin(), temp.end());
for(auto& e : temp) e.push_back(a[a.size()-1]);
res.insert(res.end(), temp.begin(), temp.end());
return res;
}
return {};
}
int main() {
// your code goes here
cout << to_str(power_set({1,2,3})) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment