Equal sums (1)
Write a program that, given an integer number s and n integer numbers x_1, … , x_n, prints all the subsets (maybe with repeated numbers, but using every x_i at most once) whose sum is exactly s.
Input: An integer number s, followed by a number n > 0, followed by x_1, …, x_n.
Output: Print all the subsets whose sum is s that can be made up with x_1, …, x_n.
You can print in any order both the solutions and the elements inside each solution.
For this exercise, simple backtracking solutions are accepted. No optimizations/pruning are required.
// Equal sums (1)
#include<iostream>
#include<vector>
using namespace std;
using VI = vector<int>;
using VB = vector<bool>;
void write(VB& sol, VI& values){
int n = sol.size();
<< "{";
cout bool first = true;
for (int i = 0; i < n; ++i){
if (sol[i]){
<< (first ? "" : ",") << values[i];
cout = false;
first }
}
<< "}" << endl;
cout }
void bt(int k, int part_sum,VB& sol, VI& values, int s){
int n = sol.size();
if (k == n){
if (part_sum == s) write(sol,values);
}
else{
[k] = false;
sol(k+1, part_sum, sol, values, s);
bt[k] = true;
sol(k+1, part_sum + values[k], sol, values, s);
bt}
}
int main(){
int s, n;
>> s >> n;
cin (n);
VI valuesfor (int i = 0; i < n; ++i){
>> values[i];
cin }
(n);
VB sol(0, 0, sol, values, s);
bt}