Sum of Subset

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

#include <iostream.

h>
#include<conio.h>
class knapsack {
public:
knapsack();
void solve();
private:
int s, *d, n;
int ExactSum(int t, int i);
};
knapsack::knapsack()
{ cout << "Knapsack problem; enter the desired sum: ";
cin >> s;
cout << "Enter n, followed by n integers:\n";
cin >> n;
d = new int[n];
for (int i=0; i<n; i++) cin >> d[i];
}
void knapsack::solve()
{ cout << "Output:\n";
if (ExactSum(s, 0)) cout << "(sum = " << s << ")\n";
else cout << "No solution.\n";
}
int knapsack::ExactSum(int t, int i)
{
if (t < 0) return 0; // No solution
if (t == 0) return 1; // Trivial solution
for (int j=i; j<n; j++)
if (ExactSum(t - d[j], j+1))
{ cout << d[j] << " "; return 1;
}
return 0;
}
int main()
{ knapsack K;
K.solve();
getch();
return 0;
}

You might also like