(Latest Revision: Mon, Apr 17, 2023) knapsackBckTrck.txt

knapsackBckTrck.txt



Backtracking Algorithm for The Knapsack Problem
(number of objects = n, weight limit = W)

Use the function below.  
Start by calling Tell_Objects(n,W)

   /* Given the set of objects {1, 2, ... , objNum} 
      and weight limit equal to "weightLim," and 
      assuming that the "table" of the knapsack problem 
      OPT values is available, tell which objects should 
      be selected to yield the greatest total value possible
      without going over the weight limit. */
Tell_Objects (objNum, weightLim)
{
    if (objNum > 0)
    {         

                /* if we can get MORE value using this object
                   than we can get NOT using it ... */
        if (table[objNum, weightLim] > table[objNum-1, weightLim])
        {
                    /* ... then we need this object.  Include it in the solution set. */
            write (objNum) ;

                   /* if there's any remaining capacity in the knapsack ... */
            if (weightLim-weight[objNum] > 0) 

                         /* ... then figure out the remaining value we can get with the 
                            remaining objects and remaining capacity in the knapsack. */
                 Tell_Objects (objNum-1, weightLim-weight[objNum]) ;
        }
                /* Otherwise, we DO NOT include this object,
                   and we use all the capacity we have
                   to get best value from the remaining object. */
        else Tell_Objects (objNum-1, weightLim) ;
    }
}