mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 09:45:04 +08:00
Optimize and Format Knapsack Memoization Algorithm (#5685)
This commit is contained in:
@ -1,5 +1,7 @@
|
||||
package com.thealgorithms.dynamicprogramming;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Recursive Solution for 0-1 knapsack with memoization
|
||||
* This method is basically an extension to the recursive approach so that we
|
||||
@ -15,10 +17,8 @@ public class KnapsackMemoization {
|
||||
int[][] dpTable = new int[numOfItems + 1][capacity + 1];
|
||||
|
||||
// Loop to initially fill the table with -1
|
||||
for (int i = 0; i < numOfItems + 1; i++) {
|
||||
for (int j = 0; j < capacity + 1; j++) {
|
||||
dpTable[i][j] = -1;
|
||||
}
|
||||
for (int[] table : dpTable) {
|
||||
Arrays.fill(table, -1);
|
||||
}
|
||||
|
||||
return solveKnapsackRecursive(capacity, weights, profits, numOfItems, dpTable);
|
||||
@ -38,7 +38,6 @@ public class KnapsackMemoization {
|
||||
if (weights[numOfItems - 1] > capacity) {
|
||||
// Store the value of function call stack in table
|
||||
dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
|
||||
return dpTable[numOfItems][capacity];
|
||||
} else {
|
||||
// case 1. include the item, if it is less than the capacity
|
||||
final int includeCurrentItem = profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable);
|
||||
@ -48,7 +47,7 @@ public class KnapsackMemoization {
|
||||
|
||||
// Store the value of function call stack in table and return
|
||||
dpTable[numOfItems][capacity] = Math.max(includeCurrentItem, excludeCurrentItem);
|
||||
return dpTable[numOfItems][capacity];
|
||||
}
|
||||
return dpTable[numOfItems][capacity];
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user