11package com .thealgorithms .dynamicprogramming ;
22
3+ import java .util .Arrays ;
4+
35/**
46 * Recursive Solution for 0-1 knapsack with memoization
57 * 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) {
1517 int [][] dpTable = new int [numOfItems + 1 ][capacity + 1 ];
1618
1719 // 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 );
2222 }
2323
2424 return solveKnapsackRecursive (capacity , weights , profits , numOfItems , dpTable );
@@ -38,7 +38,6 @@ int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOf
3838 if (weights [numOfItems - 1 ] > capacity ) {
3939 // Store the value of function call stack in table
4040 dpTable [numOfItems ][capacity ] = solveKnapsackRecursive (capacity , weights , profits , numOfItems - 1 , dpTable );
41- return dpTable [numOfItems ][capacity ];
4241 } else {
4342 // case 1. include the item, if it is less than the capacity
4443 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
4847
4948 // Store the value of function call stack in table and return
5049 dpTable [numOfItems ][capacity ] = Math .max (includeCurrentItem , excludeCurrentItem );
51- return dpTable [numOfItems ][capacity ];
5250 }
51+ return dpTable [numOfItems ][capacity ];
5352 }
5453}
0 commit comments