Subset-Sum
As our last example, we consider the subset-sum problem: find a subset of a given
set A = {a1,...,an} of n positive integers whose sum is equal to a given positive
integer d. For example, for A = {1, 2, 5, 6, 8} and d = 9, there are two solutions:
{1, 2, 6} and {1, 8}. Of course, some instances of this problem may have no
solutions.
It is convenient to sort the set’s elements in increasing order. So, we will
assume that
a1 < a2 < ... < an.
The state-space tree can be constructed as a binary tree like that in Figure 12.4 for
the instance A = {3, 5, 6, 7} and d = 15. The root of the tree represents the starting
point, with no decisions about the given elements made as yet. Its left and right
children represent, respectively, inclusion and exclusion of a1 in a set being sought.
Similarly, going to the left from a node of the first level corresponds to inclusion
of a2 while going to the right corresponds to its exclusion, and so on. Thus, a path
from the root to a node on the ith level of the tree indicates which of the first i
numbers have been included in the subsets represented by that node.
We record the value of s, the sum of these numbers, in the node. If s is equal
to d, we have a solution to the problem. We can either report this result and stop
or, if all the solutions need to be found, continue by backtracking to the node’s
parent. If s is not equal to d, we can terminate the node as nonpromising if either
of the following two inequalities holds: