I am implementing the algorithm for subset sum :
SUBSET SUM(X[1 .. n], T ):
if T = 0
return T RUE
else if T < 0 or n = 0
return FALSE
else
return SUBSET SUM(X[2 .. n], T ) ∨ SUBSET SUM(X[2 .. n], T − X[1])
Please help me out in how can I pass the reduced array X[2…n] when recursing ?
This is the code I wrote and it causes a segmentation fault:
#include <stdio.h>
int subsetsum(int a[], int sum, int size)
{
if(sum==0)
return 1;
else if (sum<0 || size <0)
return 0;
else
return (subsetsum(a+1 , sum, size-1) || subsetsum(a+1, sum - *a, size-1));
}
`
int main(int argc, char **argv)
{
int a[]={2,4,1,3,5},x;
x=subsetsum(a,6,5);
printf("%d",x);
return 0;
}
Array’s in C/C++ are implicitly decayed into pointers to the original memory buffer representing the array when used as arguments to functions. So in order to pass
X[2...n], you simply can increment the array pointer argument by1. For instance, you could do something like the following:Passing the argument
array+1on the next recursive call will increment the array pointer by one, and take a pointer pointing to the arrayX[1...n]and now make it point to the arrayX[2...n]. You would use thearray_sizeargument to detect the end of the array.Finally, you would call
subset_sumlike so: