【问题标题】:Printing subsets of a set with sum equals to k打印总和等于 k ​​的集合的子集
【发布时间】:2015-02-21 06:16:48
【问题描述】:

动态编程提供了一种非常优雅的解决子集和问题的方法。子集求和问题:求 sum = k 的子集是否存在。

但我看不到如何打印 sum = k 的所有子集。有关如何修改以下基于动态编程的函数的任何指针,如果存在所需的子集,则该函数仅检查并返回 true。请参考HERE 了解更多详情。

// Returns true if there is a subset of set[] with sun equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
    // The value of subset[i][j] will be true if there is a subset of set[0..j-1]
    //  with sum equal to i
    bool subset[sum+1][n+1];

    // If sum is 0, then answer is true
    for (int i = 0; i <= n; i++)
      subset[0][i] = true;

    // If sum is not 0 and set is empty, then answer is false
    for (int i = 1; i <= sum; i++)
      subset[i][0] = false;

     // Fill the subset table in botton up manner
     for (int i = 1; i <= sum; i++)
     {
       for (int j = 1; j <= n; j++)
       {
         subset[i][j] = subset[i][j-1];
         if (i >= set[j-1])
           subset[i][j] = subset[i][j] || subset[i - set[j-1]][j-1];
       }
     }

    /* // uncomment this code to print table
     for (int i = 0; i <= sum; i++)
     {
       for (int j = 0; j <= n; j++)
          printf ("%4d", subset[i][j]);
       printf("\n");
     } */

     return subset[sum][n];
}

【问题讨论】:

    标签: algorithm dynamic-programming subset-sum


    【解决方案1】:

    假设一个子集数组已经存在。

    我们可以编写一个递归函数来打印所有子集:generate(sum, prefixLength)。它打印前缀的所有子集,前缀长度元素总和为总和。在里面,我们需要检查两件事:如果 subset[sum - set[prefixLength]][prefixLength - 1] 为真,我们应该为 (sum - set[prefixLength], prefixLength - 1) 生成所有子集,追加当前元素给他们每个人并返回结果。如果 subset[sum][prefixLength - 1] 为真,我们应该返回为 (sum, prefixLength - 1) 生成所有集合的结果。有时这两个选项都是可能的(在这种情况下,我们需要返回第一个和第二个选项的并集)。答案是 generate(sum, n)。

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多