Skip to content

Commit 1ad5444

Browse files
authored
Update 01 - Recursive Approach (caused TLE).cpp
1 parent 172096c commit 1ad5444

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed
Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,39 @@
1-
// Solution class for 0/1 Knapsack problem
21
class Solution {
32
public:
4-
// Recursive function to solve the 0/1 Knapsack problem
3+
// Recursive function to solve the knapsack problem
54
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
5+
6+
// Base case: If we are at the first item (index 0)
87
if(index == 0){
8+
// If the weight of the first item is less than or equal to the remaining capacity, return its value
99
if(weight[0] <= capacity) return value[0];
10+
// Otherwise, return 0 because we cannot include this item in the knapsack
1011
else return 0;
1112
}
1213

13-
// Initialize variables to store the maximum value with and without the current item
14+
// Variable to store the value if we include the current item
1415
int include = 0;
15-
16-
// If the current item fits in the knapsack, consider including it
16+
// Check if the current item's weight is less than or equal to the remaining capacity
1717
if(weight[index] <= capacity) {
18-
// Recursively call the function with the remaining capacity and items
18+
// If we include the current item, reduce the capacity by the item's weight, and add its value
19+
// Recursively solve the remaining problem (remaining capacity and items)
1920
include = solve(capacity - weight[index], value, weight, index-1) + value[index];
2021
}
2122

22-
// Consider excluding the current item
23-
int exclude = solve(capacity, value, weight, index-1) + 0;
23+
// Variable to store the value if we exclude the current item
24+
int exclude = 0;
25+
// If we exclude the current item, just solve the problem with the remaining items and the same capacity
26+
exclude = solve(capacity, value, weight, index-1);
2427

25-
// Return the maximum value between including and excluding the current item
28+
// Return the maximum of the two values: including the item or excluding the item
2629
return max(include, exclude);
2730
}
2831

29-
// Function to initialize and call the recursive solve function
32+
// Function to initialize and call the recursive function to solve the knapsack problem
3033
int knapSack(int capacity, vector<int> &val, vector<int> &wt) {
3134

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
35+
int n = wt.size(); // Get the number of items
36+
// Start the recursive function with the full capacity and all items (index n-1)
3637
return solve(capacity, val, wt, n-1);
3738
}
3839
};

0 commit comments

Comments
 (0)