views:

36

answers:

1

Rather than optimize anything, I want to list all the possible - including "incomplete" - packings of the knapsack. Of course, I could loop through all subsets of the set of objects and pick the ones satisfying the weight constraint (can be improved by placing an upper bound on the size of the subsets to look through), but I'd really like something more efficient.

Thanks.

+1  A: 

First sort your objects by weight. Then recursively pack the knapsack. If the smallest weight object not yet considered does not fit, or we have no objects remaining, then add the current knapsack to our list and return, else add the current knapsack to our list for each object in the list that fits put it in and try to pack the rest of the knapsack with objects heavier than the last object we packed.

If we can pack more than one item of a given type then replace less than with less than or equal to.

If we have multiple objects of the same weight we need to sort first by weight, then by some arbitrary order, and use that.

 PackKnapsack(knapsack, objects)
   add knapsack to list
   if objects is empty return
   if smallest object does not fit return
   for each object in order from smallest to largest
      if currentobject does not fit
         break
      PackKnapsack(knapsack + currentObject, objects heavier than current object)
deinst