Skip to content

Commit caacc36

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 1ad5444 commit caacc36

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class Solution {
2+
public:
3+
// Recursive function with memoization to solve the knapsack problem
4+
int solve(int capacity, vector<int> &value, vector<int> &weight, int index, vector<vector<int>>& dp){
5+
6+
// Base case: If we are at the first item (index 0)
7+
if(index == 0){
8+
// If the weight of the first item is less than or equal to the remaining capacity, return its value
9+
if(weight[0] <= capacity) return value[0];
10+
// Otherwise, return 0 because we cannot include this item in the knapsack
11+
else return 0;
12+
}
13+
14+
// If the solution for the current subproblem (index and capacity) has already been computed, return the result from dp table
15+
if(dp[index][capacity] != -1) return dp[index][capacity];
16+
17+
// Variable to store the value if we include the current item
18+
int include = 0;
19+
// Check if the current item's weight is less than or equal to the remaining capacity
20+
if(weight[index] <= capacity) {
21+
// If we include the current item, reduce the capacity by the item's weight, and add its value
22+
// Recursively solve the remaining problem (remaining capacity and items)
23+
include = solve(capacity - weight[index], value, weight, index-1, dp) + value[index];
24+
}
25+
26+
// Variable to store the value if we exclude the current item
27+
int exclude = 0;
28+
// If we exclude the current item, just solve the problem with the remaining items and the same capacity
29+
exclude = solve(capacity, value, weight, index-1, dp);
30+
31+
// Store the result in the dp table and return the maximum of the two values: including or excluding the item
32+
dp[index][capacity] = max(include, exclude);
33+
34+
return dp[index][capacity];
35+
}
36+
37+
// Function to initialize and call the recursive function to solve the knapsack problem
38+
int knapSack(int capacity, vector<int> &val, vector<int> &wt) {
39+
40+
int n = wt.size(); // Get the number of items
41+
42+
// Create a memoization table (dp) to store solutions of subproblems
43+
// dp[i][j] will store the maximum value that can be obtained with the first i items and a knapsack capacity of j
44+
vector<vector<int>> dp(n+1, vector<int>(capacity + 1, -1));
45+
46+
// Start the recursive function with the full capacity and all items (index n-1)
47+
return solve(capacity, val, wt, n-1, dp);
48+
}
49+
};

0 commit comments

Comments
 (0)