Friday, November 18, 2016

Print sums of all subsets of a given set

#include <iostream>
#include <vector>

using namespace std;

 vector <vector <int> > getSubsets(int set[] ,int n)
{

vector <vector <int> > v;
     int nSub = 1<<n;
     for(int i=0; i<nSub; i++){
      std::vector<int> v1;
          for(int k=0; k<n; k++){
               //if the k-th bit is set
               if( (1<<k) & i){
                    v1.push_back(set[k]);
               }
          }
          v.push_back(v1);
     }
     return v;
}

void sumOfSubsets(vector <vector <int> > v)
{
// cout<<0;
for(int i = 0;i<v.size();i++){
int sum=0;
for(int j = 0;j<v[i].size();j++){
sum +=v[i][j];
}
cout<<sum<<endl;
}
}

int main (){
int set[]= {2,3,4,5};
vector <vector <int> > v =getSubsets(set,sizeof(set)/sizeof(set[0]));

sumOfSubsets(v);
}

No comments:

Post a Comment

Contributors

Translate