timothyboyboy timothyboyboy - 3 months ago 27
C++ Question

Subset sum recursion with c++

This is one of the solution of getting true or false from given set and target value

bool subsetSumExists(Set<int> & set, int target) {
if (set.isEmpty()) {
return target == 0;
} else {
int element = set.first();
Set<int> rest = set - element;
return subsetSumExists(rest, target)
|| (subsetSumExists(rest, target- element));
}
}


However, this solution will return true or false value only. How is it possible to get the element that involve in the subset(set that add together will equal to target) as well?

Do I have to use dynamic programming? Coz as i know.. recursion is building up stack actually and after the function return the value, the value inside the frame will be discarded as well.

So, is it possible to get the elements that add up equal to the target value.

Is passing an object a solution of the problem?

Thank you

Answer

First of all you can optimize your program a little bit - check if target is 0 and if it is always return true. Now what you need is to have somewhere to store the elements that you have already used. I will show you a way to do that with a global "stack"(vector in fact so that you can iterate over it), because then the code will be easier to understand, but you can also pass it by reference to the function or avoid making it global in some other way. By the way the stl container is called set not Set.

vector<int> used;
bool subsetSumExists(Set<int> & set, int target) {
    if (target == 0) {
        cout << "One possible sum is:\n";
        for (int i = 0; i < used.size(); ++i) {
          cout << used[i] << endl;
        }
        return true;
    } else if(set.empty()) {
      return false;
    }else {
        int element = set.first();
        Set<int> rest = set - element;
        used.push_back(element);
        if (subsetSumExists(rest, target- element)) {
          return true;
        } else {
          used.pop_back();
        }
        return subsetSumExists(rest, target);
    }
}

Hope this helps.