让is_subset_sum(int set[], int n, int sum)
是功能查找是否存在set[]
与相加等于总结的一个子集。 n
是set[]
中的元素数。
的is_subset_sum problem
可以被划分成两个子问题
- 包含的最后一个元素,复发对于n = N-1,总和=总和 - 将[N-1]
- 排除的最后一个元素,复发对于n = n-1。
如果上述任何一个子问题返回true,则返回true。
以下是is_subset_sum()问题的递归公式。
is_subset_sum(set, n, sum) = is_subset_sum(set, n-1, sum) || is_subset_sum(set, n-1, sum-set[n-1])
Base Cases:
is_subset_sum(set, n, sum) = false, if sum > 0 and n == 0
is_subset_sum(set, n, sum) = true, if sum == 0
我们可以在Pseudo-polynomial time使用动态编程解决问题。我们创建一个布尔二维表子集[] []并以自下而上的方式填充它。如果存在集合[0..j-1]的子集合等于i,则子集[i] [j]的值将为真,否则为假。最后,我们返回子集Σ[n]
解的时间复杂度是O(sum * n)。
在C实现
// A Dynamic Programming solution for subset sum problem
#include <stdio.h>
// Returns true if there is a subset of set[] with sun equal to given sum
bool is_subset_sum(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];
}
// Driver program to test above function
int main() {
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set)/sizeof(set[0]);
if (is_subset_sum(set, n, sum) == true)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
}
这应该在[CodeReview](http://codereview.stackexchange.com) –
数字是正数吗? –
@ThisaruGuruge这不是一个代码审查我已经提出'O(N * N * Sum)'的工作代码'现在我想改善它的时间复杂性是一个算法问题 –