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

时间:2015-03-26 15:07:38

标签: c algorithm

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

例如,如果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

3 个答案:

答案 0 :(得分:1)

对于输入{x 1 ,...,x n },返回2 n-1 (x 1 + ... + x n ),因为每个术语都出现在那么多的总和中。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

答案:

总数没有。子集是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<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);
        }
相关问题