1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void SearchSum(const vector<int>& v, unsigned i, int sum, string solution)
{
if (sum==0)
{
cout << solution << '\n';
return;
}
if (sum<0 || i==v.size())
return;
SearchSum(v, i+1, sum, solution);
SearchSum(v, i+1, sum-v[i], solution+" + "+to_string(v[i]));
}
void SubsetSum(const vector<int>& v, int sum)
{
SearchSum(v, 1, sum, ""); // Skipping v[0]
SearchSum(v, 1, sum-v[0], to_string(v[0])); // Including v[0]
}
int main()
{
vector<int> v {29, 17, 33, 21, 13, 15, 24, 20, 23};
SubsetSum(v, 100);
return 0;
}
|