I have this code for finding the subset sum of positive values and everywhere I searched I only see positive integers or a program written in java in advanced level. I want to know how to implement that my C program would work with negative numbers. Actually, I want it to find sum that is 0. I had an idea
- Take the minimum value in the set, call it
k. - Add each element in the set by the absolute value of
k. - Add sum by the absolute value of
k. - Perform the algorithm.
But I found that this wont work. Take the set (-5, 10) and see if any subset adds up to 5. We would convert (-5, 10) -> (0, 15) and 5->10. -5+10=5, but 0+15 != 10
A lot of ideas I searched on the internet but can't find the answer.
#include <stdio.h>
typedef int bool;
#define true 1
#define false 0
bool isSubsetSum(int set[], int n, int sum) {
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
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, -2, 12, 5, 8 };
int sum = 0;
int i;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset");
else
printf("No subset");
return 0;
}
typedef int bool; #define true 1 #define false 0good lord, no. Pick a language, please. - WhozCraig