Suggest an algorithm for finding the sum of all subsets of a set.
For example, if k=3
and the subsets are {1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}
Answer:
Total no. of Subsets are 2^n.
As we don't require an empty set, so total required subsets are 2^n - 1.
Now all we have to do is simply get all possible subsets.
This algorithm will help.
void main()
{
//Total no. of elements in set = n;
//Let's say the Set be denoted as P[n]
//declare a global variable sum and initialize to 0.
for(int i=1;i<=n;i++)
{
int r = nCi;
//here, r = nCi or you can say n combinations i
//it's good to write an extra function named something like "nCi" to evaluate nCi and call it when required.
//define a new two dimensional array of size "r","i", say s[r][i]
for(int k=0;k<r;k++)
{
//define a function to get all combination array for s[r][i] using "i" elements out of total "n"
//This link will help you with best of code for this particular function
//<http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/>
//now for every particular s[r][i], do this
for(int j=0;j<i;j++)
{
sum = sum + s[r][j];
}
}
}
//display total output
printf("%d",sum);
}
Each element appears the same number of times, which happens to be 2n-1 where n is number of elements. So the answer is: count sum of elements in the set and multiply it by 2n-1
For an input {x1, …, xn}, return 2n-1 (x1 + … + xn), since each term appears in that many sums.