FUNCTION BESTKNAPSACK
Best Knapsack algorithm for the knapsack (3) problem (This is
the algorithm "backpack" of page 308 of Brassard and Bratley)
/*
A call to bestKnapsack(1,W) returns the best value that can be
achieved filling a knapsack that has weight limit W with items
having item numbers in the range [1..n]. The tables
weight[1..n] and value[1..n] give the weight and value of each
item type.
This is a recursive function.
More generally a call to bestKnapsack(1stAllowedItem, remWtLim)
returns the best value that can be achieved filling a knapsack
that has (remaining) weight limit remWtLim with items having
item numbers in the range [1stAllowedItem..n].
The idea of the function is to "generate and test". Each
possible set of items is generated and then tested to see what
value it yields.
The structure of the algorithm has been designed to avoid
generating the same set of items more than once. Depending on
how an algorithm like this one is set up, it is conceivable
that it might generate two different *sequences* of item choices
that yield the same set of items. For example, the sequences
(1,2,1) and (1,1,2) yield the same *set* of items. It is
inefficient to generate and test both of these sequences.
A call to bestKnapsack(1,W) generates all non-decreasing
sequences of item numbers in the range [1..n]. That way, the
same *set* never corresponds to more than one *sequence* of
items.
*/
function bestKnapsack (1stAllowedItem, remWtLim) ;
{
bestValue = 0;
for itemType = 1stAllowedItem to n do
{
if weight[itemType] <= remWtLim
/*
check the best value we can get by taking one of the
current items types, and filling the rest of the
knapsack with items numbered no lower than the current
item number. (This is how we get non-decreasing
sequences.)
*/
then bestValue =
max ( bestValue,
value[itemType] +
bestKnapsack(itemType, remWtLim-weight[itemType] );
}
return bestValue ;
}