Print sums of all subsets of a given set
Problem summary : Print all subset sums of a given set of integers
My approach is to store previous results and use them to calculate new (similar idea as DP).
SubsetSum.cpp
#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;
}
You can find the code on Github Gist and compilation result at OnlineGdb.
Along with code, please also comment on the algorithm itself.
Is it advisable to store previous result in practice (since it takes 2ⁿ space)?
Also, is there any scope of improving time or space without trading-off the other?