Knapsack
Knapsack
Given n items of
integer weights: w1 w2 … wn
values: v1 v2 … vn
a knapsack of integer capacity W
find most valuable subset of the items that fit into the knapsack
B
Example 4: Coin-collecting by robot
Several coins are placed in cells of an n×m board. A robot,
located in the upper left cell of the board, needs to collect as
many of the coins as possible and bring them to the bottom
right cell. On each step, the robot can move either one cell to
the right or one cell down from its current location.
1 2 3 4 5 6
5
Solution to the coin-collecting problem
Let F(i,j) be the largest number of coins the robot can collect
and bring to cell (i,j) in the ith row and jth column.
The recurrence:
F(i, j) = max{F(i-1, j), F(i, j-1)} + cij for 1 ≤ i ≤ n, 1 ≤ j ≤ m
where cij = 1 if there is a coin in cell (i,j), and cij = 0 otherwise
5
Example