function PackageItem(name, weight, value, count) {
this.name = name;
this.weight = weight;
this.value = value;
this.count = count;
}
function get01PackageAnswerFor2degree(bagItems, bagsize, countForItem) {
var bagMatrix = [];
var item;
var answers = [];
for (var i = 0; i <= bagItems.length; i++) {
bagMatrix[i] = [];
for (var j = bagsize; j >= 0; j--) {
bagMatrix[i][j] = [];
answers[j] = [];
for (var k = countForItem; k >= 0; k--) {
bagMatrix[i][j][k] = 0;
answers[j][k] = [];
}
}
}
for (var tmpBagsize = 1; tmpBagsize <= bagsize; tmpBagsize++) {
for (var tmpCount = 1; tmpCount <= countForItem; tmpCount++) {
for (var tmpItemID = 0; tmpItemID < bagItems.length; tmpItemID++) {
item = bagItems[tmpItemID];
if (item.weight > tmpBagsize) {
if (tmpItemID == 0) {
bagMatrix[tmpItemID][tmpBagsize][tmpCount] = 0;
} else {
bagMatrix[tmpItemID][tmpBagsize][tmpCount] = bagMatrix[tmpItemID - 1][tmpBagsize][tmpCount];
}
} else {
if (item.count > tmpCount) {
if (tmpItemID == 0) {
bagMatrix[tmpItemID][tmpBagsize][tmpCount] = 0;
} else {
bagMatrix[tmpItemID][tmpBagsize][tmpCount] = bagMatrix[tmpItemID - 1][tmpBagsize][tmpCount];
}
} else {
var itemInBag;
if (tmpItemID == 0) {
bagMatrix[tmpItemID][tmpBagsize][tmpCount] = item.value;
continue;
} else {
itemInBag = bagMatrix[tmpItemID - 1][tmpBagsize - item.weight][tmpCount - item.count] + item.value; //向上向下找都无所谓,只要安一定的顺序找就行了
bagMatrix[tmpItemID][tmpBagsize][tmpCount] = Math.max(bagMatrix[tmpItemID - 1][tmpBagsize][tmpCount], itemInBag); //比较下现在的情况是不是比不动要好 0+6 < 7 就不
}
}
}
}
}
}
return bagMatrix[bagItems.length - 1][bagsize][countForItem];
}
var nameArr = ['a', 'b', 'c', 'd', 'e'];
var weightArr = [3, 2, 6, 5, 4];
var valueArr = [6, 3, 13, 4, 6];
var countArr = [1, 1, 1, 1, 1]
var bagItems = [];
for (var i = 0; i < nameArr.length; i++) {
var bagItem = new PackageItem(nameArr[i], weightArr[i], valueArr[i], countArr[i]);
bagItems[i] = bagItem;
}
let answ = get01PackageAnswerFor2degree(bagItems, 11, 3);
console.log(answ);
多重背包问题
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 题目 有N种物品和一个容量为V的背包。第i种物品最多有n[i]件可用,每件费用是c[i],价值是w[i]。求解将哪...
- 可以套模板的多重背包问题 因为背包容量和物品种类数都最大10000,暴力dp 需要一亿次,本来以为可能超一秒了。结...
- 我在进行一些互联网公司的技术笔试的时候,对于我来说最大的难题莫过于最后的那几道编程题了,这对算法和数据结构有一定程...