编辑代码

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