|
| 1 | +/* Subset sum problem is to find subset of elements that are selected from a given set whose sum adds up to a given number K.Given n distinct positive integers (called weights), find all |
| 2 | +combinations of these numbers whose sum is m. |
| 3 | +solved this problem using approach of backtracking . |
| 4 | +Here backtracking approach is used for trying to select a valid subset when an item is not valid, we will backtrack to get the previous subset and add another element to get the solution. |
| 5 | + Recursive backtracking code for sum of subset problem |
| 6 | +It find all the subset of w[1:n] that sum to m */ |
| 7 | +#include<stdio.h> |
| 8 | +void sumofsub(int s,int k,int r,int m,int w[],int x[],int n); |
| 9 | + |
| 10 | +int main() |
| 11 | +{ |
| 12 | + int x[20],w[20],i,n,s,r=0,m; |
| 13 | + |
| 14 | + printf("enter no of tuples: "); |
| 15 | + scanf("%d",&n); |
| 16 | + |
| 17 | + for(i=1;i<=n;i++) |
| 18 | + { |
| 19 | + printf("weight of x%d: ",i); |
| 20 | + scanf("%d",&w[i]); |
| 21 | + r=r+w[i]; |
| 22 | + x[i]=0; |
| 23 | + } |
| 24 | + |
| 25 | + printf("enter value of m: "); |
| 26 | + scanf("%d",&m); |
| 27 | + |
| 28 | + sumofsub(0,1,r,m,w,x,n); |
| 29 | + |
| 30 | +} |
| 31 | + |
| 32 | +void sumofsub(int s,int k,int r,int m,int w[],int x[],int n) |
| 33 | +{ |
| 34 | + int i; |
| 35 | + // generate left child |
| 36 | + x[k]=1; |
| 37 | + |
| 38 | + if(s+w[k]==m) //Subset found |
| 39 | + { |
| 40 | + printf("considered tuple: ("); |
| 41 | + for(int i=1;i<=n;i++)// There is no recursive call here |
| 42 | + printf("%d,",x[i]); |
| 43 | + printf(")\n"); |
| 44 | + } |
| 45 | + |
| 46 | + else if(s+w[k]+w[k+1]<=m)// generate right child |
| 47 | + sumofsub(s+w[k],k+1,r-w[k],m,w,x,n); |
| 48 | + |
| 49 | + if((s+r-w[k]>=m)&&(s+w[k+1]<=m)) |
| 50 | + { |
| 51 | + x[k]=0; |
| 52 | + sumofsub(s,k+1,r-w[k],m,w,x,n); |
| 53 | + } |
| 54 | +} |
| 55 | +/* |
| 56 | +Test case 1 |
| 57 | +Input: |
| 58 | +enter no of tuples: 4 |
| 59 | +weight of x1: 10 |
| 60 | +weight of x2: 20 |
| 61 | +weight of x3: 30 |
| 62 | +weight of x4: 40 |
| 63 | +enter value of m: 50 |
| 64 | +Output: |
| 65 | +considered tuple: (1,0,0,1) |
| 66 | +considered tuple: (1,1,1,0) |
| 67 | +Test case 2 |
| 68 | +Input |
| 69 | +enter no of tuples: 5 |
| 70 | +weight of x1: 7 |
| 71 | +weight of x2: 10 |
| 72 | +weight of x3: 15 |
| 73 | +weight of x4: 18 |
| 74 | +weight of x5: 20 |
| 75 | +enter value of m: 35 |
| 76 | +Output |
| 77 | +considered tuple: (1,1,0,1,0) |
| 78 | +considered tuple: (0,0,1,0,1) |
| 79 | + |
| 80 | +Time complexity=O(2*N) |
| 81 | +*/ |
0 commit comments