package genius.base;
public class PackageAnswer {
/**
* @param m 表示背包的最大容量
* @param n 表示商品的个数
* @param w 表示商品重量数组 weight
* @param p 表示商品价值数组 price
*/
public static int[][] BackPack(int m, int n, int[] w, int[] p) {
int c[][] = new int[n + 1][m + 1];
/**
* 关键是考虑在什么情况下要放入背包中。
*/
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (w[i - 1] <= j) {
c[i][j] = Math.max(c[i - 1][j - w[i - 1]] + p[i - 1],c[i - 1][j]);
} else
c[i][j] = c[i - 1][j];
}
}
return c;
}
public static void main(String[] args) {
int m = 10;
int n = 3;
int w[] = {2, 8, 6, 7};
int p[] = {4, 5, 6, 2};
int c[][] = BackPack(m, n, w, p);
for (int i = 1; i <=n; i++) {
for (int j = 1; j <=m; j++) {
System.out.print(c[i][j]+"\t");
if(j==m){
System.out.println();
}
}
}
}
}
0 4 4 4 4 4 4 4 4 4
0 4 4 4 4 4 4 5 5 9
0 4 4 4 4 6 6 10 10 10