I got this problem with subset sum, in which as the term says, i need to find all numbers that combined gives a certain number S. The problem is that I need to combine both + and -. The problem itself is as follows:
For starters, I did the simple subset sum, the following code:A set of natural numbers is given. Generate all the subsets of this set joined by alternating + and - operators which sum up to exactly S. .
I/O description. Input: enumeration of elements in the set, on one line, then sum on one line e.g.
1 3 5 7 2 6
0
Output: enumeration of elements resulting in the given sum, e.g.
1-3+2
1+3-6
5-7+2
1+5-6
...
I got several ideas on how to resolve this, like for example, if it is possible for C to see the numbers as both positive or negative integers, i don't know if that can be implemented, maybe something like a complement of the numbers? Any other ideas would be much appreciated.Code:#include<conio.h> #include<stdio.h> #include<stdlib.h> #define NMAX 10 void display(int res[],int k){ int i; printf("\n"); for(i=0; i<=k; i++){ printf("%d ",res[i]); } } int partial_sol(int y[],int m,int s){ int i=0, sum=0; for(i=0; i<=m; i++){ sum+=y[i]; } if(sum<=s){ return1; } return0; } int complete_sol(int y[],int m,int s){ int i=0, sum=0; for(i=0; i<=m; i++){ sum+=y[i]; } if(sum==s){ return1; } return0; } void backtrack(int k,int n,int s,intset[],int res[]){ int j; for(j=k; j<n; j++){ res[k]=set[j]; if(partial_sol(res, k, s)==1){ if(complete_sol(res, k , s)==1){ display(res, k); } elseif(k<n) backtrack(k+1, n, s,set, res); } } } void main(){ int n, s, i; printf("No. of elements: "); scanf("%d",&n); printf("\n Sum: "); scanf("%d",&s); intset[n],res[n]; for(i=0; i<n; i++){ printf("Elem no. %d: ", i); scanf("%d",&set[i]); res[i]=0; } backtrack(0, n, s,set, res); }