编辑代码

public class Knapsack {

    private static final int MAX_WEIGHT = 10;
    private int[] weights = {2, 3, 4, 5};
    private int[] values = {3, 4, 5, 6};
    private int maxProfit = Integer.MIN_VALUE;

    public Knapsack() {
        backtrack(0, 0, 0);
        System.out.println("Maximum Profit: " + maxProfit);
    }

    private void backtrack(int index, int currentWeight, int currentProfit) {
        if (currentWeight > MAX_WEIGHT) {
            return;
        }

        if (index == weights.length) {
            maxProfit = Math.max(maxProfit, currentProfit);
            return;
        }

        // Include current item
        backtrack(index + 1, currentWeight + weights[index], currentProfit + values[index]);

        // Exclude current item
        backtrack(index + 1, currentWeight, currentProfit);
    }

    public static void main(String[] args) {
        new Knapsack();
    }
}