1
1
// 0-1 Knapsack problem - Dynamic programming
2
- // #include <bits/stdc++.h>
3
2
#include < iostream>
4
3
5
4
// void Print(int res[20][20], int i, int j, int capacity)
6
- // {
7
- // if(i==0 || j==0)
8
- // {
9
- // return;
10
- // }
11
- // if(res[i-1][j]==res[i][j-1])
12
- // {
13
- // if(i<=capacity)
14
- // {
15
- // cout<<i<<" ";
16
- // }
5
+ // {
6
+ // if(i==0 || j==0)
7
+ // {
8
+ // return;
9
+ // }
10
+ // if(res[i-1][j]==res[i][j-1])
11
+ // {
12
+ // if(i<=capacity)
13
+ // {
14
+ // std:: cout<<i<<" ";
15
+ // }
17
16
//
18
- // Print(res, i-1, j-1, capacity-i);
19
- // }
20
- // else if(res[i-1][j]>res[i][j-1])
21
- // {
22
- // Print(res, i-1,j, capacity);
23
- // }
24
- // else if(res[i][j-1]>res[i-1][j])
25
- // {
26
- // Print(res, i,j-1, capacity);
27
- // }
28
- // }
17
+ // Print(res, i-1, j-1, capacity-i);
18
+ // }
19
+ // else if(res[i-1][j]>res[i][j-1])
20
+ // {
21
+ // Print(res, i-1,j, capacity);
22
+ // }
23
+ // else if(res[i][j-1]>res[i-1][j])
24
+ // {
25
+ // Print(res, i,j-1, capacity);
26
+ // }
27
+ // }
29
28
30
29
int Knapsack (int capacity, int n, int weight[], int value[]) {
31
30
int res[20 ][20 ];
@@ -35,14 +34,14 @@ int Knapsack(int capacity, int n, int weight[], int value[]) {
35
34
res[i][j] = 0 ;
36
35
} else if (weight[i - 1 ] <= j) {
37
36
res[i][j] = max (value[i - 1 ] + res[i - 1 ][j - weight[i - 1 ]],
38
- res[i - 1 ][j]);
37
+ res[i - 1 ][j]);
39
38
} else {
40
39
res[i][j] = res[i - 1 ][j];
41
40
}
42
41
}
43
42
}
44
- // Print(res, n, capacity, capacity);
45
- // cout<<"\n";
43
+ // Print(res, n, capacity, capacity);
44
+ // std:: cout<<"\n";
46
45
return res[n][capacity];
47
46
}
48
47
0 commit comments