Assignment #6, COP-3337

Do Exercise 8.24. A sketch of an algorithm is provided below. Note that this algorithm may take exponential time, meaning that it is impractical for large amounts of input. However, you must use a recursive algorithm to receive credit.

The Routines

Provide two functions containsSubset with the following signatures:
bool containsSubset( const vector<int> & a, int k );
bool containsSubset( const vector<int> & a, int k, int low, int high );
The first version returns true if there is a subset of a that sums to k. The second version returns true if there is a subset of a, using only items in the subarray a[low...high], that sums to k. Both versions print out the elements that form the matching subset. It should be a simple matter to implement the first version of containsSubset by making a call to the second version. The second version is the recursive algorithm that will be described below.

Provide a main that will prompt for k and the elements of array a, and then make a call to containsSubset and either output the matching sequence or an indication that there is no match.

The Recursive Algorithm

Recall that the function declaration is
bool containsSubset( const vector<int> & a, int k, int low, int high );
Here are the basic cases:

Base Case

If low>high, then there is no element in the subarray, and containsSubset should return true only if k==0.

Recursive Case

Otherwise there is one or more element. In that case, there is a matching sequence if either of the following cases is true:
  1. containsSubset( a, k, low+1, high ) is true
  2. containsSubset( a, k - A[ low ], low+1, high ) is true
The first case says that there is a match using elements in positions low+1 to high The second case says that there is a match using element A[low] plus other elements in positions low+1 to high. In the second case, A[low] is one of the elements that will be part of the match and can be printed.

What to Submit

Place your source code in a single file. The whole program should fit in a page. Submit your source code and run on the data sets below. You may assume that the array will contain at most 30 numbers.

Data Sets

The first two sets are guaranteed to have matches for any value of k (that is not too large). The third set is not.

Powers of 2

Input sequence: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536.
k: 100000

Fibonacci Numbers

Input sequence: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946.
k: 12000

Nothing Special

Input sequence: 2134, 5436, 8796, 6578, 1234, 9999, 4534, 1492, 1996, 1997, 3859, 3337, 3530, 1999, 6405.
k: 11000; k: 12000; k: 13000; k: 14000;