1 year ago
#327361
xKostmand
Recursively finding subset sum
I am practicing on recursion and i wanted to try a very popular problem for recursion, the subset sum problem, but i wanted a little catch. I also want to print the subset if it exists.
#include <stdio.h>
int isSubsetSum(int set[], int n, int sum){
if (sum == 0)
return 1;
if (n == 0)
return 0;
if (set[n - 1] > sum)
return isSubsetSum(set, n - 1, sum);
return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);
}
int main(){
int set[] = { 3, 34, -4, -12, 5, 2, 1, 7, 9 };
int sum = 0;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum) == 1)
printf("Found a subset with given sum\n");
else
printf("No subset with given sum\n");
return 0;
}
This is my code so far. How would i implement it. I have been stuck on this problem for quite some days and i cant figure it out.
c
recursion
subset-sum
0 Answers
Your Answer