Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathKnapsackMemoization.java
More file actions
Latest commit
53 lines (42 loc) · 2.16 KB
/
Copy pathKnapsackMemoization.java
File metadata and controls
53 lines (42 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
packagecom.thealgorithms.dynamicprogramming;
importjava.util.Arrays;
/**
* Recursive Solution for 0-1 knapsack with memoization
* This method is basically an extension to the recursive approach so that we
* can overcome the problem of calculating redundant cases and thus increased
* complexity. We can solve this problem by simply creating a 2-D array that can
* store a particular state (n, w) if we get it the first time.
*/
publicclassKnapsackMemoization {
intknapSack(intcapacity, int[] weights, int[] profits, intnumOfItems) {
// Declare the table dynamically
int[][] dpTable = newint[numOfItems + 1][capacity + 1];
// Loop to initially fill the table with -1
for (int[] table : dpTable) {
Arrays.fill(table, -1);
}
returnsolveKnapsackRecursive(capacity, weights, profits, numOfItems, dpTable);
}
// Returns the value of maximum profit using recursive approach
intsolveKnapsackRecursive(intcapacity, int[] weights, int[] profits, intnumOfItems, int[][] dpTable) {
// Base condition
if (numOfItems == 0 || capacity == 0) {
return0;
}
if (dpTable[numOfItems][capacity] != -1) {
returndpTable[numOfItems][capacity];
}
if (weights[numOfItems - 1] > capacity) {
// Store the value of function call stack in table
dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
} else {
// case 1. include the item, if it is less than the capacity
finalintincludeCurrentItem = profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable);
// case 2. exclude the item if it is more than the capacity
finalintexcludeCurrentItem = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
// Store the value of function call stack in table and return
dpTable[numOfItems][capacity] = Math.max(includeCurrentItem, excludeCurrentItem);
}
returndpTable[numOfItems][capacity];
}
}