Skip to content

Commit 172096c

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 5bf5282 commit 172096c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Solution class for 0/1 Knapsack problem
2+
class Solution {
3+
public:
4+
// Recursive function to solve the 0/1 Knapsack problem
5+
int solve(int capacity, vector<int> &value, vector<int> &weight, int index){
6+
// Base case: if we've considered all items, return the value of the last item
7+
// if it fits in the knapsack, otherwise return 0
8+
if(index == 0){
9+
if(weight[0] <= capacity) return value[0];
10+
else return 0;
11+
}
12+
13+
// Initialize variables to store the maximum value with and without the current item
14+
int include = 0;
15+
16+
// If the current item fits in the knapsack, consider including it
17+
if(weight[index] <= capacity) {
18+
// Recursively call the function with the remaining capacity and items
19+
include = solve(capacity - weight[index], value, weight, index-1) + value[index];
20+
}
21+
22+
// Consider excluding the current item
23+
int exclude = solve(capacity, value, weight, index-1) + 0;
24+
25+
// Return the maximum value between including and excluding the current item
26+
return max(include, exclude);
27+
}
28+
29+
// Function to initialize and call the recursive solve function
30+
int knapSack(int capacity, vector<int> &val, vector<int> &wt) {
31+
32+
// Get the number of items
33+
int n = wt.size();
34+
35+
// Call the recursive solve function with the initial capacity and all items
36+
return solve(capacity, val, wt, n-1);
37+
}
38+
};

0 commit comments

Comments
 (0)