The Subset Sum Problem is a classic problem in computer science and combinatorial optimization. It involves finding all subsets of a given set of integers that sum to a specific target value. The problem can be solved using recursion and backtracking or dynamic programming.
Here’s a C++ implementation to find all subsets of a given set that sum up to a target value:
#include <iostream>
#include <vector>
using namespace std;
void findSubsets(vector<int>& arr, int target, vector<int>& current, int index) {
if (target == 0) {
cout << "{ ";
for (int num : current) {
cout << num << " ";
}
cout << "}" << endl;
return;
}
if (target < 0 || index == arr.size()) {
return;
}
current.push_back(arr[index]);
findSubsets(arr, target - arr[index], current, index + 1);
current.pop_back();
findSubsets(arr, target, current, index + 1);
}
int main() {
vector<int> arr = {3, 34, 4, 12, 5, 2};
int target = 9;
vector<int> current;
cout << "Subsets with sum " << target << " are:\n";
findSubsets(arr, target, current, 0);
return 0;
}
Subsets with sum 9 are:
{ 3 4 2 }
{ 4 5 }
arr
contains the elements for which we want to find subsets. The target
variable holds the desired sum.This implementation effectively finds all subsets of a given set that sum to a specified target, using a recursive backtracking approach.