Equal sums (3)
Write a program that, given a natural number s and n natural numbers x_1, \dots, x_n, prints all the subsets (maybe with repeated numbers, but using every x_i at most once) whose sum is exactly s.
Input: Input consists of a natural number s, followed by a number n > 0, followed by x_1, \dots , x_n.
Output: Print all the subsets whose sum is s that can be made up with x_1, \dots , x_n.
You can print in any order both the solutions and the elements inside each solution.
This is the same as Equal sums (1) we saw few moments ago. The only difference is that now a very simple algorithm can be too slow. We have to do some pruning.
To get an idea of some pruning that might be useful, think on the input
5
5
1 1 1 1 1
Suppose you are exploring a branch were you chose the first 1
but not the second. Can this be completed to a full solution? Why?
//Equal sums (3)
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int n,s;
<int> x;
vector
void write(const vector<bool>& sol){
int n = sol.size();
<< "{";
cout = "";
string aux for (int i = 0; i < n; ++i){
if (sol[i]){
<< aux << x[i];
cout = ",";
aux }
}
<< "}" << endl;
cout }
void bt(int k, vector<bool>& sol, int part_sum, int rest_sum){
if (part_sum > s or part_sum + rest_sum < s) return;
if (k == n){
if (part_sum == s) write(sol);
}
else{
[k] = false;
sol(k+1, sol, part_sum, rest_sum - x[k]);
bt[k] = true;
sol(k+1, sol, part_sum + x[k], rest_sum - x[k]);
bt}
}
int main(){
>> s >> n;
cin = vector<int>(n);
x int sum = 0;
for (int i = 0; i< n; ++i){
>> x[i];
cin += x[i];
sum }
<bool> sol(n,true);
vector(0, sol, 0, sum);
bt}