/* Solving existence and any solution variation of subset sum problem * Author: Xiaolan Zhang * Data: 10/10/2024 */ #include #include using namespace std; /* Check whether there is a subset of numbers from X that add up to T @param: T sum to make @param: X a vector of values @param: next: which value in X we are making decision on next @return: true if one can make sum T using a subset from X[next...X.size()-1] false if otherwise */ bool subset_sum(int T, vector X, int next){ //base case if (T==0) return true; else if (T<0) return false; else if (next==X.size()) return false; else { //general case //make the next decision: to include X[next] or not? //try include it: then we want to see if we can make the smaller sum // using the rest of the values in X [next+1...] bool success = subset_sum(T - X[next], X, next+1); if (success) return true; //no need to explore the other option //if not success, try the other option: exclude X[next]... success = subset_sum(T, X , next+1); //we commit to not include X[next], //so try to make T using the rest of values in X return success; } } void PrintVector(vector result) { cout <<" Result contains: "; for (int i=0;i subset_sum(int T, vector X, int next, bool & succeed){ vector result; //initialized to empty vector //helping with tracing cout <<"subset_sum (T="<> a; //base case if (T==0){ succeed = true; cout <<"subset_sum (T="< numbers = {7, 14, 15, 10}; int sum = 29; /* cout <<"Entering a sum to make using values from 7, 14, 15, 10:\n"; cin >>sum; if (subset_sum (sum, numbers, 0)) cout <<"we can make a sum of :"<>sum; bool succeed; vector result = subset_sum (sum, numbers, 0, succeed); if (succeed){ cout <<"we can make a sum of :"<