-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0_1_knapsack.cpp
96 lines (78 loc) · 2.61 KB
/
0_1_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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
problem link: https://www.codingninjas.com/codestudio/problems/0-1-knapsack_920542
A thief is robbing a store and can carry a maximal weight of W into his knapsack.
There are N items and the ith item weighs wi and is of value vi.
Considering the constraints of the maximum weight that a knapsack can carry, you have to find and return the maximum value that a thief can generate by stealing items.
*/
#include <iostream>
#include <vector>
using namespace std;
class RecSolution{
int f(int idx, int W, vector<int> &weight, vector<int> &value)
{
if(idx == 0)
{
if(weight[idx]<=W)
return value[0];
else
return 0;
}
int not_pick = f(idx - 1, W, weight, value);
int pick = -1e9;
if(weight[idx] <= W)
pick = value[idx] + f(idx - 1, W - weight[idx], weight, value);
return max(pick, not_pick);
}
int knapsack(vector<int> weight, vector<int> value, int n, int maxWeight)
{
// Write your code here
return f(n - 1, maxWeight, weight, value);
}
};
class MemoSolution{
int f(int idx, int W, vector<int> &weight, vector<int> &value, vector<vector<int>> &dp)
{
if (idx == 0)
{
if (weight[idx] <= W)
return value[0];
else
return 0;
}
if(dp[idx][W]!=-1)
return dp[idx][W];
int not_pick = f(idx - 1, W, weight, value, dp);
int pick = -1e9;
if (weight[idx] <= W)
pick = value[idx] + f(idx - 1, W - weight[idx], weight, value, dp);
return dp[idx][W] = max(pick, not_pick);
}
int knapsack(vector<int> weight, vector<int> value, int n, int maxWeight)
{
// Write your code here
vector<vector<int>> dp(n, vector<int>(maxWeight + 1, -1));
return f(n - 1, maxWeight, weight, value, dp);
}
};
class TabulationSol{
public:
int knapsack(vector<int> weight, vector<int> value, int n, int maxWeight)
{
// DONT INITIALISE with -1
vector<vector<int>> dp(n, vector<int>(maxWeight + 1, 0));
for (int i = weight[0]; i <= maxWeight; i++)
dp[0][i] = value[0];
for (int idx = 1; idx < n; idx++)
{
for (int wt = 0; wt <= maxWeight; wt++)
{
int not_pick = dp[idx - 1][wt];
int pick = -1e9;
if (weight[idx] <= wt)
pick = value[idx] + dp[idx - 1][wt - weight[idx]];
dp[idx][wt] = max(pick, not_pick);
}
}
return dp[n - 1][maxWeight];
}
};