I am new to C (1.5 months of training), and our college professor asked us to find a solution to the dynamic programming of the Subset Sum problem (along with two others), but I followed his instructions, m went in cycles on how to actually find (print) ) the requested subsets. Can someone help me understand how this works and how to find all subsets?
For the code below, the table is {3,2,1,2,4,3,4,1}, and the subsets must be added up to 7.
CHANGE! â I changed the source code to find out how many subsets exist, adding up to a certain value (in our case 7, and the subsets 20). I repeat that I need help finding all the subsets (combinations) that sum up to a value (in this case 7).
In the above case, this means that the code will be able to print 20 subsets, which:
Subset 1: 3 2 1 1
Subset 2: 3 2 2
Subset 3: 3 1 2 1
Subset 4: 3 1 3
Subset 5: 3 4
Subset 6: 3 3 1
Subset 7: 3 4
Subset 8: 2 1 4
Subset 9 : 2 1 3 1
Subset 10: 2 1 4
Subset 11: 2 2 3
Subset 12: 2 4 1
Subset 13: 2 4 1
Subset 14: 1 2 4
Subset 15: 1 2 3 1
Subset 16: 1 2 4
Subset 17 : 2 4 1
Subset 18: 2 4 1
Subset 19: 4 3
Subset 20: 3 4
C , , . :
x[i][j]=x[i-1][j];
if(j>=y[i-1]) x[i][j]+=x[i-1][j-y[i-1]];
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long set[] = {3,2,1,2,4,3,4,1};
long sum =7;
long n = sizeof(set)/sizeof(set[0]);
iter_subset_sum(set, n, sum);
return 0;
}
int iter_subset_sum (int *y, long n, long sum) {
int i,j,k,**x;
x=malloc((n+1)*sizeof(long**));
for(i=0;i<=n;i++)
x[i]=malloc((sum+1)*sizeof(long*));
for (i=0; i<=n; i++)
x[i][0] = 1;
for (i=1; i<=sum; i++)
x[0][i] =0;
for (i=1; i<=n; i++) {
for (j=1; j<=sum; j++){
x[i][j]=x[i-1][j];
if(j>=y[i-1])
x[i][j]+=x[i-1][j-y[i-1]]; } }
for (i = 0; i <= n; i++){
for (j = 0; j <= sum; j++)
printf ("%4d", x[i][j]);
printf("\n");
}
printf("There are %d subsets :", x[n][sum]);
}
! , , "" C...