-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path125.backpack-ii.cpp
104 lines (98 loc) · 2.55 KB
/
125.backpack-ii.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
97
98
99
100
101
102
103
104
// Tag: Backpack DP, Dynamic Programming/DP
// Time: O(N^2)
// Space: O(N^2)
// Ref: -
// Note: -
// There are `n` items and a backpack with size `m`.
// Given array `A` representing the size of each item and array `V` representing the value of each item.
//
// What's the maximum value can you put into the backpack?
//
// **Example 1:**
//
// Input:
// ```
// m = 10
// A = [2, 3, 5, 7]
// V = [1, 5, 2, 4]
// ```
// Output:
// ```
// 9
// ```
// Explanation:
//
// Put A[1] and A[3] into backpack, getting the maximum value V[1] + V[3] = 9
//
// **Example 2:**
//
// Input:
// ```
// m = 10
// A = [2, 3, 8]
// V = [2, 5, 8]
// ```
// Output:
// ```
// 10
// ```
// Explanation:
//
// Put A[0] and A[2] into backpack, getting the maximum value V[0] + V[2] = 10
//
// 1. `A[i], V[i], n, m` are all integers.
// 2. You can not split an item.
// 3. The sum size of the items you want to put into backpack can not exceed `m`.
// 4. Each item can only be picked up once
// 5. $m <= 1000$\
// $len(A),len(V)<=100$
class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param a: Given n items with size A[i]
* @param v: Given n items with value V[i]
* @return: The maximum value
*/
int backPackII(int m, vector<int> &a, vector<int> &v) {
// write your code here
int n = a.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int weight = a[i - 1];
int val = v[i - 1];
if (j >= weight) {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight] + val);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n][m];
}
};
class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param a: Given n items with size A[i]
* @param v: Given n items with value V[i]
* @return: The maximum value
*/
int backPackII(int m, vector<int> &a, vector<int> &v) {
// write your code here
int n = a.size();
vector<int> dp(m + 1, 0);
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 1; j--) {
int weight = a[i - 1];
int val = v[i - 1];
if (j >= weight) {
dp[j] = max(dp[j], dp[j - weight] + val);
}
}
}
return dp[m];
}
};