Skip to content

Commit 44de201

Browse files
committed
update bag problem
1 parent 1ab11f7 commit 44de201

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

solution-category/dp/bag-problem.js

+44-1
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,47 @@ function bagProblem2() {
7777
return dp[capacity];
7878
}
7979

80-
console.log(bagProblem2());
80+
console.log(bagProblem2());
81+
82+
/**
83+
* 背包问题 - 暴力解法
84+
* @param {*} capacity
85+
* @param {*} weights
86+
* @param {*} values
87+
* @param {number} n 物品数量
88+
*/
89+
function crashBag(capacity, weights, values, n) {
90+
// capacity: 5
91+
// weights: [2,3,4]
92+
// values: [3,4,5]
93+
94+
let weightSum = 0;
95+
let valueSum = 0;
96+
let maxValue = 0;
97+
98+
const backTracking = (start) => {
99+
if (weightSum > capacity) return;
100+
101+
maxValue = Math.max(maxValue, valueSum);
102+
103+
for (let i = start; i < n; i++) {
104+
weightSum += weights[i];
105+
valueSum += values[i];
106+
console.log(weightSum)
107+
backTracking(i + 1);
108+
weightSum -= weights[i];
109+
valueSum -= values[i];
110+
console.log(weightSum)
111+
}
112+
}
113+
backTracking(0);
114+
115+
return maxValue;
116+
}
117+
118+
const maxValue = helper(5, [2,3,4], [3,4,5], 3);
119+
120+
// console.log('max value:', maxValue);
121+
122+
123+

0 commit comments

Comments
 (0)