Subset Sum
Understand the various techniques used to solve the subset sum problem efficiently.
We'll cover the following
Subset sum problem and its description
Let’s consider a more complicated problem called subset sum: Given a set X of positive integers and target integer T, is there a subset of elements in X that add up to T? 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 add up 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: and . The resulting recursive algorithm is shown below.
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy