Skip to content

Commit d820fc0

Browse files
authored
Update 02_Knapsack_memoization.cpp
1 parent fd36623 commit d820fc0

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

02_Knapsack_memoization.cpp

+18-18
Original file line numberDiff line numberDiff line change
@@ -7,39 +7,39 @@ int t[D][D]; // DP matrix
77

88
int Knapsack(int wt[], int val[], int W, int n) {
99
// base case
10-
if (n == 0 || W == 0)
10+
if (n == 0 || W == 0) {
1111
return 0;
12-
12+
}
1313
// if already calculated
14-
if (t[n][W] != -1)
15-
return t[n][W];
16-
17-
// else calculate
18-
else {
19-
if (wt[n - 1] <= W)
20-
t[n][W] = max(val[n - 1] + Knapsack(wt, val, W - wt[n - 1], n - 1),Knapsack(wt, val, W, n - 1));
21-
else if (wt[n - 1] > W)
22-
t[n][W] = Knapsack(wt, val, W, n - 1);
23-
14+
if (t[n][W] != -1) {
2415
return t[n][W];
2516
}
17+
if (wt[n - 1] <= W) {
18+
t[n][W] = max(val[n - 1] + Knapsack(wt, val, W - wt[n - 1], n - 1),Knapsack(wt, val, W, n - 1));
19+
} else if (wt[n - 1] > W) {
20+
t[n][W] = Knapsack(wt, val, W, n - 1);
21+
}
22+
return t[n][W];
2623
}
2724

2825
signed main() {
2926
int n; cin >> n; // number of items
3027
int val[n], wt[n]; // values and wts array
31-
for (int i = 0; i < n; i++)
28+
for (int i = 0; i < n; i++) {
3229
cin >> wt[i];
33-
for (int i = 0; i < n; i++)
30+
}
31+
for (int i = 0; i < n; i++) {
3432
cin >> val[i];
33+
}
3534
int W;
3635
cin >> W; // capacity
3736

3837
// matrix initialization
39-
for (int i = 0; i <= n; i++)
40-
for (int j = 0; j <= W; j++)
38+
for (int i = 0; i <= n; i++) {
39+
for (int j = 0; j <= W; j++) {
4140
t[i][j] = -1; // initialize matrix with -1
42-
41+
}
42+
}
4343
cout << Knapsack(wt, val, W, n) << endl;
4444
return 0;
45-
}
45+
}

0 commit comments

Comments
 (0)