Your knapsack (or possibly your back) has the capacity to hold kilograms ( is a nonnegative integer). You are presented with a collection of categories of goodies that are free for the taking, category items have weight and value (weights and values also nonnegative integers). Fill your knapsack so that you can carry off ( is not exceeded) the maximum value. Since you're allowed to take more than one item of the same type, you can express your answer as a list of indices such that , and you maximize .
Here's an example you may be able to solve without any high-powered algorithm. Suppose = 11, , , , , and , , , .
Solving this using greedy algorithms (add the most valuable item that fits, etc.) doesn't yield an optimal solution. Follow the DP approach to try to identify how an optimal solution is related to optimal solutions for subproblems.
If is an optimal solution, then we can at least say that must be an optimal solution for a knapsack with capacity . This suggests we can define an array , where is the maximum value that can be carried in a knapsack with capacity . If we can find , then we're done. What we already know yields a recurrence:
V[0] = 0; for (int j = 1; j <= C; j++) { V[j] = V[j-1]; for (int i = 0; i < n; i++) { if (w[i] <= j && v[i] + V[j-w[i]] > V[j]) { V[j] = v[i] + V[j-w[i]]; } } }Now you know the value of the loot you can carry away in your knapsack, but you still need to work out the actual composition. One way to do this is by creating an extra array L[j], containing the last choice of article added to get V[j].