-
Notifications
You must be signed in to change notification settings - Fork 1
/
0-1 knapsack.cpp
56 lines (42 loc) · 1.23 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
// Assignment 4 : Write a program to solve a 0-1 Knapsack problem using dynamic programming.
#include <bits/stdc++.h>
using namespace std;
int knapSackRec(int W, int wt[], int val[], int index, int** dp)
{
if (index < 0)
return 0;
if (dp[index][W] != -1)
return dp[index][W];
if (wt[index] > W) {
dp[index][W] = knapSackRec(W, wt, val, index - 1, dp);
return dp[index][W];
}
else {
dp[index][W] = max(val[index]
+ knapSackRec(W - wt[index], wt, val,
index - 1, dp),
knapSackRec(W, wt, val, index - 1, dp));
return dp[index][W];
}
}
int knapSack(int W, int wt[], int val[], int n)
{
int** dp;
dp = new int*[n];
for (int i = 0; i < n; i++)
dp[i] = new int[W + 1];
for (int i = 0; i < n; i++)
for (int j = 0; j < W + 1; j++)
dp[i][j] = -1;
return knapSackRec(W, wt, val, n - 1, dp);
}
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
cout << knapSack(W, weight, profit, n);
return 0;
}
// Time complexity - O(N * W)