【发布时间】: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