Givenn_kind of items with size Aiand value Vi(each item has an infinite number available) and a backpack with size_m. What's the maximum value can you put into the backpack?
Example
Given 4 items with size[2, 3, 5, 7]and value[1, 5, 2, 4], and a backpack with size10. The maximum value is15.
Note
给定 n 种具有大小 A[i] 和价值 V[i] 的物品(每个物品可以取用无限次)和一个大小为 m 的一个背包, 你可以放入背包里的最大价值是多少?
注意事项:你不能将物品分成小块, 选择的项目的总大小应小于或等于 m。
虽然题目声称每种物品都有无限件,但实际上每种物品最多有V / cap[i]件,因此这个问题相当于一个num[i] = V / cap[i]的多重背包问题。
Code
public class Solution {
public int backPackIII(int[] A, int[] V, int m) {
int n = A.length;
int[] f = new int[m + 1];
for (int i = 0; i < n; ++i) {
for (int k = 1; k * A[i] <= m; ++k) {
for (int j = m; j >= A[i]; --j) {
f[j] = Math.max(f[j], f[j - A[i]] + V[i]);
}
}
}
return f[m];
}
}
//完全背包最优解
public class Solution {
public int backPackIII(int[] A, int[] V, int m) {
int n = A.length;
int[] f = new int[m + 1];
for (int i = 0; i < n; ++i) {
for (int j = A[i]; j <= m; ++j) {
f[j] = Math.max(f[j], f[j - A[i]] + V[i]);
}
}
return f[m];
}
}