Subset Sum
Discover how to solve the subset sum problem using backtracking in C++. This lesson guides you through designing and implementing a recursive algorithm that determines if subsets adding up to a target sum exist, including constructing such subsets when possible. Gain insight into the problem's base cases, recursive strategy, and computational complexity to enhance your algorithmic problem-solving skills.
We'll cover the following...
The subset sum problem and its description
Let’s consider a more complicated problem called subset sum. Given a set of positive integers and target integer , is there a subset of elements in that adds up to ? Notice that there can be more than one such subset. For example, if and , the answer is True, because the subsets and and and all sum to 15. On the other hand, if and , the answer is False.
There are two trivial cases. If the target value is zero, then we can immediately return True because the empty set is a subset of every set , and the elements of the empty set add up to zero. On the other hand, if , or if but the set is empty, then we can immediately return False.
For the general case, consider an arbitrary element . (We’ve already handled the case where is empty.) There is a subset of that sums to if, and only if, one of the following statements is true:
- There is a subset of that includes and whose sum is .
- There is a subset of that excludes and whose sum is .
In the first case, there must be a subset of that sums to ; in the second case, there must be a subset of that sums to . So, we can solve by reducing it to two simpler instances: ...