How to find all subsets in the sum of a subset (with dynamic programming) in C

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...

+3
1
#include <stdio.h>
int iscan(int a[],int n,int sum){
    int f[sum+1],m=0,i,j,k,el,o=0;
    for(i=1;i<=sum;i++)f[i]=0;f[0]=1;
    for(i=0;i<n;i++){
        el=a[i];
        if(el>sum)continue;
        m=m+el>sum?sum:m+el;
        for(k=m-el,j=m;k>=0;j--,k--){
            if(f[k]){
                /* f[j]=el;*/ //old only last conest
                            push_toarray_of_stack(on j position ,item size of el);;//this pseudocode is hint for u homework*********** so and change printing all combination after builing array_of_stack  of conection

            }
        }
        if(!f[sum])continue;
        k=sum;
        while(k){
            printf("%d ",f[k]);
            k-=f[k];
        }
        printf("%s\n","");
        //exit(0); 
            o++;
    }
    //printf("%s\n","can't");
    return o;
}

int main(){
  int set[] = {1, 3, 2, 4, 2, 6, 5};
  int sum = 5;
  return iscan(set,sizeof(set)/sizeof(set[0]),sum);
}
+1

All Articles