import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Knapsack {
static class Item {
int weight;
int value;
public Item(int weight, int value) {
this.weight = weight;
this.value = value;
}
}
public static void main(String[] args) {
Item[] items = {
new Item(10, 60),
new Item(20, 100),
new Item(30, 120)
};
int capacity = 50;
List<Item> bestSolution = knapsack(items, capacity);
System.out.println("最佳方案:");
int totalWeight = 0;
int totalValue = 0;
for (Item item : bestSolution) {
System.out.println(" 物品重量:" + item.weight + ", 物品价值:" + item.value);
totalWeight += item.weight;
totalValue += item.value;
}
System.out.println(" 总重量:" + totalWeight);
System.out.println(" 总价值:" + totalValue);
}
private static List<Item> knapsack(Item[] items, int capacity) {
List<Item> bestSolution = new ArrayList<>();
int maxValue = 0;
knapsackHelper(items, capacity, 0, new ArrayList<>(), 0, bestSolution, maxValue);
return bestSolution;
}
private static void knapsackHelper(Item[] items, int capacity, int index, List<Item> currentSolution, int currentValue,
List<Item> bestSolution, int maxValue) {
if (index == items.length) {
if (currentValue > maxValue) {
bestSolution.clear();
bestSolution.addAll(currentSolution);
maxValue = currentValue;
}
return;
}
Item currentItem = items[index];
knapsackHelper(items, capacity, index + 1, currentSolution, currentValue, bestSolution, maxValue);
if (capacity >= currentItem.weight) {
currentSolution.add(currentItem);
currentValue += currentItem.value;
knapsackHelper(items, capacity - currentItem.weight, index + 1, currentSolution, currentValue, bestSolution, maxValue);
currentSolution.remove(currentItem);
currentValue -= currentItem.value;
}
}
}