1
1
package com .thealgorithms .dynamicprogramming ;
2
2
3
+ import java .util .Arrays ;
4
+
3
5
/**
4
6
* Recursive Solution for 0-1 knapsack with memoization
5
7
* This method is basically an extension to the recursive approach so that we
@@ -15,10 +17,8 @@ int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) {
15
17
int [][] dpTable = new int [numOfItems + 1 ][capacity + 1 ];
16
18
17
19
// Loop to initially fill the table with -1
18
- for (int i = 0 ; i < numOfItems + 1 ; i ++) {
19
- for (int j = 0 ; j < capacity + 1 ; j ++) {
20
- dpTable [i ][j ] = -1 ;
21
- }
20
+ for (int [] table : dpTable ) {
21
+ Arrays .fill (table , -1 );
22
22
}
23
23
24
24
return solveKnapsackRecursive (capacity , weights , profits , numOfItems , dpTable );
@@ -38,7 +38,6 @@ int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOf
38
38
if (weights [numOfItems - 1 ] > capacity ) {
39
39
// Store the value of function call stack in table
40
40
dpTable [numOfItems ][capacity ] = solveKnapsackRecursive (capacity , weights , profits , numOfItems - 1 , dpTable );
41
- return dpTable [numOfItems ][capacity ];
42
41
} else {
43
42
// case 1. include the item, if it is less than the capacity
44
43
final int includeCurrentItem = profits [numOfItems - 1 ] + solveKnapsackRecursive (capacity - weights [numOfItems - 1 ], weights , profits , numOfItems - 1 , dpTable );
@@ -48,7 +47,7 @@ int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOf
48
47
49
48
// Store the value of function call stack in table and return
50
49
dpTable [numOfItems ][capacity ] = Math .max (includeCurrentItem , excludeCurrentItem );
51
- return dpTable [numOfItems ][capacity ];
52
50
}
51
+ return dpTable [numOfItems ][capacity ];
53
52
}
54
53
}
0 commit comments