【问题标题】:Finding the sum of all subsets of a given set查找给定集合的所有子集的总和
【发布时间】:2015-03-26 15:07:38
【问题描述】:

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

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

【问题讨论】:

  • 我建议你尝试一些东西,而不是要求直接解决看起来像家庭作业的问题
  • @Cocoop,首先这不是作业问题,我正在努力寻找一种有效的算法。
  • “不是作业”可以。尽管如此,SO 的理念是“如果您表现出一些研究努力,我们会为您提供帮助”。无论如何,幸运的是,您已经免费获得了一些不错的潜在客户。

标签: c algorithm


【解决方案1】:

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

【讨论】:

  • 也许您的问题定义得不够好,但我知道您的输入已设置。对于集合 {3},答案应该是 3 而不是 4。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    回答:

    总数子集是 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);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多