20 lines
785 B
Plaintext
20 lines
785 B
Plaintext
0/1 Knapsack
|
|
============
|
|
|
|
1) Table: weights [1,3,4,5], values [1,4,5,7], capacity 7. dp[i][w] = best value with the first i items
|
|
w = 0 1 2 3 4 5 6 7
|
|
none 0 0 0 0 0 0 0 0
|
|
item 1 0 1 1 1 1 1 1 1
|
|
item 2 0 1 1 4 5 5 5 5
|
|
item 3 0 1 1 4 5 6 6 9
|
|
item 4 0 1 1 4 5 7 8 9
|
|
answer = dp[4][7] = 9 (weights 3 + 4, values 4 + 5)
|
|
|
|
2) One row, capacity loop direction: weights [5,4,6,3], values [10,40,30,50], capacity 10
|
|
backward loop (each item used once) -> 90
|
|
forward loop, same code otherwise -> 150 (the weight-3 item is reused three times: 3 x 50)
|
|
|
|
3) Calls made: 22 items, capacity 60, best value 357
|
|
naive recursion -> 1003985 calls
|
|
memoized -> 1794 calls
|