Here is my code that print elements of subset whose sum is equal to the given sum,(it works only for positive numbers):
#include <bits/stdc++.h>
using namespace std;
void traverse(vector<int> vec) {
for(int a=0; a < vec.size(); a++)
cout << vec[a] << " ";
cout << endl;
}
void possible(vector<int> vec, int sum, vector<int> now) {
if(sum == 0) {
traverse(now);
}
else if(sum < 0) {
now.clear();
}
else if(sum > 0 && vec.size() > 0) {
for(int a = 0; a < vec.size(); a++) {
now.push_back(vec[a]);
vector<int> vecc(vec.begin() + a + 1, vec.end());
possible(vecc, sum - vec[a], now);
now.erase(now.end() - 1);
}
}
}
int main() {
int n, sum;
cin >> n >> sum;
vector<int> vec(n), now;
for(int a = 0; a < n; a++)
cin >> vec[a];
possible(vec, sum, now);
return 0;
}
Is there any chance of improvements or any faster way to improve run time?
Any Dynamic problem solution for this?