Commit 8e132774 authored by Fokion Zervoudakis's avatar Fokion Zervoudakis

Update tabulated implementation and Javadoc. Add comments.

parent 31d72a87
......@@ -14,8 +14,8 @@ class DpKnapsack {
Uses recursive (top-down) dynamic programming with memoization to
calculate solve the knapsack problem.
<ul>
<li>time_worst=O(n)
<li>space_worst=O(n)
<li>time_worst=O(mn)
<li>space_worst=O(mn)
</ul>
@param w the item weights
......@@ -36,7 +36,7 @@ class DpKnapsack {
return M.get(key);
} else {
int max;
if (i == v.length) {
if (i == w.length) {
max = 0;
} else {
int a = helper(w, v, i + 1, size);
......@@ -54,8 +54,8 @@ class DpKnapsack {
Uses iterative (bottom-up) dynamic programming with tabulation to solve
the knapsack problem.
<ul>
<li>time_worst=O(n)
<li>space_worst=O(n)
<li>time_worst=O(mn)
<li>space_worst=O(mn)
</ul>
@param w the item weights
......@@ -67,20 +67,16 @@ class DpKnapsack {
*/
@Tabulation
int max(int[] w, int[] v, int size) {
int m = v.length;
int[][] memo = new int[m + 1][size + 1];
for (int i = m - 1; i >= 0; i--) {
for (int j = 0; j < size + 1; j++) {
if (i == m) {
memo[i][j] = 0;
} else {
int a = memo[i + 1][j];
int b = (j >= w[i]) ? memo[i + 1][j - w[i]] + v[i] : 0;
memo[i][j] = Math.max(a, b);
}
int m = w.length;
int[][] M = new int[m + 1][size + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= size; j++) {
int a = M[i - 1][j];
int b = (j >= w[i - 1]) ? M[i - 1][j - w[i - 1]] + v[i - 1] : 0;
M[i][j] = Math.max(a, b);
}
}
return memo[0][size];
return M[m][size];
}
}
}
......@@ -99,6 +99,12 @@ class DpKnapsackTest {
assertEquals(40, tab.max(w, v, 4));
assertEquals(50, tab.max(w, v, 5));
assertEquals(60, tab.max(w, v, 6));
// size=7: 0, 1, 2, 3, 4, 5, 6, 7
// w=3,v=30: 0, 0, 0, 30, 30, 30, 30, 30
// w=1,v=10: 0, 10, 10, 30, 40, 40, 40, 40
// w=2,v=20: 0, 10, 20, 30, 40, 50, 60, 60
assertEquals(60, tab.max(w, v, 7));
}
......@@ -120,6 +126,15 @@ class DpKnapsackTest {
assertEquals(110, tab.max(w, v, 11));
assertEquals(120, tab.max(w, v, 12));
assertEquals(130, tab.max(w, v, 13));
// size=14: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
// w=3,v=30: 0, 0, 0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30
// w=1,v=10: 0, 10, 10, 30, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
// w=2,v=20: 0, 10, 20, 30, 40, 50, 60, 60, 60, 60, 60, 60, 60, 60, 60
// w=1,v=10: 0, 10, 20, 30, 40, 50, 60, 70, 70, 70, 70, 70, 70, 70, 70
// w=4,v=40: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 110, 110, 110
// w=2,v=20: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 130
assertEquals(130, tab.max(w, v, 14));
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment