Last active
July 26, 2019 11:33
-
-
Save Gaurav-Singh-97/6174257361b6c0e12dfd163d527ada61 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
//using namespace std; | |
bool isPowerOf2 (long long x) | |
{ | |
/* First x in the below expression is for the case when x is 0 */ | |
return x && (!(x&(x-1))); | |
} | |
std::vector<long long> subsetSums(std::vector<int> set) | |
{ | |
long long total = 1<<set.size(); //total number of subsets = size of power set = 2^n | |
std::vector<long long> sums(total, 0); | |
sums[1] = set[0]; | |
//std::cout << sums[0] << std::endl; | |
//std::cout << sums[1] << std::endl; | |
int effectiveBits = 1, prevPowOf2 = 1; | |
for (long long i = 2; i < total; ++i) | |
{ | |
if (isPowerOf2(i)) | |
{ | |
++effectiveBits; | |
prevPowOf2 *= 2; | |
} | |
//std::cout << "e = " << effectiveBits << "\tp = " << prevPowOf2 << std::endl; | |
sums[i] = set[effectiveBits-1] + sums[i-prevPowOf2]; | |
//std::cout << sums[i] << "\n"; | |
} | |
return sums; | |
} | |
// Driver code | |
int main() | |
{ | |
std::vector<int> set = {5, 4, 3}; | |
std::vector<long long> sumsOfAllSubsets = subsetSums(set); | |
for (auto sum : sumsOfAllSubsets) | |
std::cout << sum << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment