查找给定集合的所有子集的总和

建议一种算法,用于查找集合中所有子集的总和。

例如,如果k=3且子集为{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}则求和子集是{1}+{2}+{3}+{1+2}+{1+3}+{2+3}+{1+2+3}=24

对于输入{x 1 ,…,x n },返回2 n-1 (x 1 + … + x n ),因为每个项出现在那么多个和中。

每个元素出现的次数相同,恰好是2 n-1 ,其中n是元素的数量。 所以答案是:计算集合中元素的总和并乘以2 n-1

回答:

总数没有。 子集是2 ^ n。
因为我们不需要空集,所以总需要的子集是2 ^ n – 1.现在我们所要做的就是获得所有可能的子集。
这个算法会有所帮助。

  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 //now for every particular s[r][i], do this for(int j=0;j