class Item {
constructor(name, value, weight) {
this.name = name
this.weight = weight;
this.value = value;
}
}
function knapsackBranchAndBound(items, capacity) {
items.sort((a, b) => b.value / b.weight - a.value / a.weight);
let maxValue = 0;
let bestCombination = [];
function branchAndBound(index, currentWeight, currentValue, included) {
if (currentValue > maxValue) {
maxValue = currentValue;
bestCombination = [...included];
}
if (index < items.length) {
branchAndBound(index + 1, currentWeight, currentValue, [...included]);
if (currentWeight + items[index].weight <= capacity) {
branchAndBound(index + 1, currentWeight + items[index].weight, currentValue + items[index].value, [...included, items[index]]);
}
}
}
branchAndBound(0, 0, 0, []);
return {
maxValue,
bestCombination
};
}
const items = [
new Item("IPhone", 2000, 1),
new Item("吉他", 1500, 1),
new Item("笔记本电脑", 2000, 3),
new Item("音箱", 3000, 4)
];
const capacity = 8;
const result = knapsackBranchAndBound(items, capacity);
console.log("最大价值", result.maxValue);
console.log("最佳组合", result.bestCombination);