-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_knapsack.cpp
74 lines (53 loc) · 1.74 KB
/
01_knapsack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// https://www.codingninjas.com/codestudio/problems/0-1-knapsack_920542?topList=love-babbar-dsa-sheet-problems&leftPanelTab=0&utm_source=youtube&utm_medium=affiliate&utm_campaign=Lovebabbar
// simp;e recursive approach
#include <bits/stdc++.h>
int solve(vector<int> &weight, vector<int> &value, int ind, int capacity){
// base case
if(ind==0){
if(weight[0]<=capacity){
return value[0];
}
else{
return 0;
}
}
int include = 0;
if(weight[ind] <= capacity){
include = value[ind] + solve(weight,value,ind - 1,capacity - weight[ind]);
}
int exclude = 0 + solve(weight,value,ind - 1,capacity);
int ans = max(include,exclude);
return ans;
}
int knapsack(vector<int> weight, vector<int> value, int n, int maxWeight)
{
return solve(weight,value,n-1,maxWeight);
}
// Top Down: Recursion + Memoization
#include <bits/stdc++.h>
int solve(vector<int> &weight, vector<int> &value, int ind, int capacity,vector<vector<int> > &dp){
// base case
if(ind==0){
if(weight[0]<=capacity){
return value[0];
}
else{
return 0;
}
}
if(dp[ind][capacity]!= -1){
return dp[ind][capacity];
}
int include = 0;
if(weight[ind] <= capacity){
include = value[ind] + solve(weight,value,ind - 1,capacity - weight[ind],dp);
}
int exclude = 0 + solve(weight,value,ind - 1,capacity,dp);
dp[ind][capacity] = max(include,exclude);
return dp[ind][capacity];
}
int knapsack(vector<int> weight, vector<int> value, int n, int maxWeight)
{
vector<vector<int> > dp(n,vector<int>(maxWeight + 1, -1));
return solve(weight,value,n-1,maxWeight,dp);
}