next up previous
Next: Up: Previous:

Dynamic Programming for 0-1 Knapsack Problem

Exercise 17.2-2

For this algorithm, let c[i,w] = value of solution for items 1..i and maximum weight w.

c[i,w] = \(\left\{ \begin{array}{ll}
0 & {\rm if} \; i = 0 \; {\rm or} \; w = 0 \\
c[i...
...1,w]) &
{\rm if} \; i > 0 \; {\rm and} \; w \geq w_i \\
\end{array} \right.\)

DP-01K(v, w, n, W)
1
$\;\;\;\;\;$for w = 0 to W
2
$\;\;\;\;\;$ $\;\;\;\;\;$c[0,w] = 0
3
$\;\;\;\;\;$for i = 1 to n
4
$\;\;\;\;\;$ $\;\;\;\;\;$c[i,0] = 0
5
$\;\;\;\;\;$ $\;\;\;\;\;$for w = 1 to W
6
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$if w[i] $\leq$ w
7
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$then if v[i] + c[i-1,w-w[i]] > c[i-1,w]
8
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$then c[i,w] = v[i] + c[i-1,w-w[i]]
9
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$else c[i,w] = c[i-1,w]
10
$\;\;\;\;\;$ $\;\;\;\;\;$ $\;\;\;\;\;$else c[i,w] = c[i-1,w]

The run time performance of this algorithm is $\Theta(nW)$.


next up previous
Next: Up: Previous: