Skip to content

Instantly share code, notes, and snippets.

@saikatkumardey
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saikatkumardey/1139acffea7bf104ef69 to your computer and use it in GitHub Desktop.
Save saikatkumardey/1139acffea7bf104ef69 to your computer and use it in GitHub Desktop.
Generate all possible sub-set sum
#include <iostream>
using namespace std;
//Given an array, generate all possible sum
int main(void)
{
int array[]= {1,2,3};
int N= sizeof(array)/sizeof(int);
for(int mask=0; mask < 1<<N; mask++) //generate numbers from 0 to 2^N-1.
//Number of subsets for a N-length set = 2^N (including the empty set)
{
int sum=0;
//Suppose that mask=6, in binary: 6 = 110
//The for-loop below works like this:
//check 0th bit, it is 0 so, no action, sum=0
//check 1st bit, it is 1, so add array[1] to sum
//check 2nd bit, it is 1, so add array[2] to sum
//ultimately, sum = 0 + array[1] + array[2]
//similarly, for 7=111
//all bits are set
//so, sum= array[0] + array[1] + array[2]
//N= number of elements in the array = number of bits of mask that should be checked
for(int i=0; i<N; i++ ) //check each bit of mask
{
if(mask & (1<<i)) //if the i-th bit is set, then add it to sum
{
sum+=array[i];
}
}
cout<<sum<<endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment