165
The knapsack problem
Let’s start filling in the grid.
Like this, each cell in the grid will contain a list of all the items that fit
into the knapsack at that point.
Let’s look at the next cell. Here you have a knapsack of capacity 2 lb.
Well, the guitar will definitely fit in there!
The same for the rest of the cells in this row. Remember, this is the first
row, so you have
only
the guitar to choose from. You’re pretending
that
the other two items aren’t available to steal right now.
At
this point, you’re probably confused.
Why
are you doing this for
knapsacks with a capacity of 1 lb, 2 lb, and so on,
when the problem
talks about a 4 lb knapsack? Remember how I told you that dynamic
programming starts with a small problem and builds up to the big
problem? You’re solving subproblems here
that will help you to solve
the big problem. Read on, and things will become clearer.