Problem:有5个物品,放到容量为10的包里,使得装入包中的物品价值最大 weight[] ={2,2,6,5,4}; value[] = {6,3,5,4,6}; capacity = 10;
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 0 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 |
1 | 0 | 0 | 6 | 6 | 9 | 9 | 9 | 9 | 9 | 9 | 9 |
2 | 0 | 0 | 6 | 6 | 9 | 9 | 9 | 9 | 11 | 11 | 14 |
3 | 0 | 0 | 6 | 6 | 9 | 9 | 9 | 10 | 11 | 13 | 14 |
4 | 0 | 0 | 6 | 6 | 9 | 9 | 12 | 12 | 15 | 15 | 15 |
package DP;
import java.util.Arrays;
public class ZeroOneKnapSackProblem {
public static int maxVal(int[] value,int[] weight,int capacity){
if (weight.length == 0)
return 0;
int dp[][] = new int[weight.length][capacity+1];
System.out.println(dp.length);
System.out.println(dp[0].length);
for (int j=0;j<capacity+1;j++){
if (j>=weight[0]){
dp[0][j] = value[0];
} else {
dp[0][j] = 0;
}
}
for (int i=1;i<weight.length;i++){
for (int j=0;j<capacity+1;j++){
if (j>=weight[i]){
dp[i][j] = Math.max(dp[i-1][j],value[i]+dp[i-1][j-weight[i]]);
} else {
dp[i][j] = dp[i-1][j];
}
}
}
for (int i=0;i<weight.length;i++){
System.out.println(Arrays.toString(dp[i]));
}
return dp[weight.length-1][capacity];
}
public static void main(String[] args){
int weight[] ={2,2,6,5,4};
int value[] = {6,3,5,4,6};
int capacity = 10;
System.out.println(maxVal(value,weight,capacity));
}
}