public class test3 {
public static void main(String[] args) {
String[] fruits = {"苹果", "香蕉", "橘子", "猕猴桃"};
int[] weights = {15, 18, 10, 9};
int[] values = {300, 180, 150, 270};
int capacity = 20;
int[][] dp = new int[fruits.length + 1][capacity + 1];
for (int i = 1; i <= fruits.length; i++) {
for (int w = 1; w <= capacity; w++) {
if (weights[i - 1] <= w) {
dp[i][w] = Math.max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
printStrategy(dp, fruits, weights, values, capacity);
}
private static void printStrategy(int[][] dp, String[] fruits, int[] weights, int[] values, int capacity) {
int i = fruits.length;
int w = capacity;
System.out.println("背包装水果的策略:");
while (i > 0 && w > 0) {
if (dp[i][w] != dp[i - 1][w]) {
System.out.println("装入 " + fruits[i - 1] + ",重量:" + weights[i - 1] + "kg,价值:" + values[i - 1]);
w -= weights[i - 1];
}
i--;
}
}
}