Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 49162f6

Browse files
committed
feat: 01背包-递归版
1 parent e4dbb95 commit 49162f6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

动态规划/01背包-递归版.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
*
3+
* @param {number[]} w 物品的重量集合
4+
* @param {number[]} v 物品的价值集合
5+
* @param {number} C 背包容量
6+
*/
7+
function knapsack01(w, v, C) {
8+
let n = w.length - 1;
9+
10+
return bestValue(w, v, n, C);
11+
}
12+
13+
// 用 [0...index] 的物品
14+
// 填充容积为c的背包的最大价值
15+
function bestValue(w, v, index, c) {
16+
if (index < 0 || c <= 0) return 0;
17+
18+
let max = bestValue(w, v, index - 1, c);
19+
20+
// 装背包之前需要先判断这个当前背包还可以容纳下这个物品
21+
if (c >= w[index]) {
22+
max = Math.max(
23+
// 不装进背包
24+
max,
25+
// 装进背包
26+
v[index] + bestValue(w, v, index - 1, c - w[index])
27+
);
28+
}
29+
30+
return max;
31+
}
32+
33+
console.log(knapsack01([1, 2, 3], [4, 5, 15], 3));

0 commit comments

Comments
 (0)