-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16-0-1背包问题.js
More file actions
54 lines (46 loc) · 1.33 KB
/
16-0-1背包问题.js
File metadata and controls
54 lines (46 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 0-1背包问题
let allObjects = [{
value: 4,
volume: 2
}, {
value: 5,
volume: 3
}, {
value: 7,
volume: 4
}, {
value: 8,
volume: 5
}, {
value: 9,
volume: 6
}];
function getMaxValue(bagVolume, objects) {
// 没有可选的东西
if (objects.length === 0) {
return {
objects: [],
value: 0,
volume: 0
}
}
const left = objects.slice(1);
// 第一件物品的体积比背包剩余空间大,放不下,直接算后面的最优解
if (objects[0].volume > bagVolume) {
return getMaxValue(bagVolume, left);
}
// 在第一件物品放得下的情况下,考虑第一件物品放进去后,剩余物品的最优解
const nextMaxValue = getMaxValue(bagVolume - objects[0].volume, left);
nextMaxValue.objects.push(objects[0]);
nextMaxValue.value += objects[0].value;
nextMaxValue.volume += objects[0].volume;
// 在第一件物品放得下的情况下,考虑第一件物品不放进去后,剩余物品的最优解
const nextMaxValueNo1 = getMaxValue(bagVolume, left);
// 前面两种情况算出来后比较那种最好
if (nextMaxValue.value > nextMaxValueNo1.value) {
return nextMaxValue;
} else {
return nextMaxValueNo1;
}
}
console.log(getMaxValue(12, allObjects));