pgm8 Subsetsum
pgm8 Subsetsum
h>
int count = 0;
int main()
{
int n; //No. of elements in set
int d; //Required subset sum
int s[10]; //Array: Elements in the set
int i; //index variable
int sum = 0;
if(count == 0)
printf("No solutions possible.");
}
return 0;
}
sum = 0;
k = 1; //Take first element
x[k] = 1; //Add first element to subset
while(1)
{
if(k <= n && x[k] == 1) //k in range(1 to n) & kth element selected
{
//If required subset sum found then print solution
if(sum+s[k] == d)
{
count++;
printf("Solution is \n");
for(i = 1; i <= n; i++)
{
if(x[i] == 1)
printf("%5d", s[i]);
}
printf("\n");
x[k] = 0; //Proceed to find next solution
}
else if(sum + s[k] < d) //If subset sum is < required sum,
sum += s[k]; //then add the current element to
//subset
else
x[k] = 0; //If subset sum is morethan required
//sum, then remove the current
element
}
else
{
k--; //Bring k within range
while(k > 0 && x[k] == 0) //Find recently added element to
k--; //subset and remove it
/*
Run1:
Enter the value of n5
Enter the set in increasing order
1
2
3
4
5
Enter the maximum subset value of d: 7
Solution is
1 2 4
Solution is
2 5
Solution is
3 4
Run2:
Enter the value of n3
Enter the set in increasing order
4
5
6
Enter the maximum subset value of d: 7
No solutions possible.
*/