Finding the sum of all subsets of a given set

前端 未结 3 779
时光取名叫无心
时光取名叫无心 2020-12-22 15:18

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}

相关标签:
3条回答
  • 2020-12-22 16:00

    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);
            }
    
    0 讨论(0)
  • 2020-12-22 16:03

    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

    0 讨论(0)
  • 2020-12-22 16:17

    For an input {x1, …, xn}, return 2n-1 (x1 + … + xn), since each term appears in that many sums.

    0 讨论(0)
提交回复
热议问题