Skip to content

Commit fd0f1d3

Browse files
committed
knapSack recursice
1 parent 5261d58 commit fd0f1d3

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

chapter11/08-LongestCommonSubsequenceRecursive.html chapter11/06-KnapSackProblemRecursive.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55
<title></title>
66
</head>
77
<body>
8-
8+
<script src="06-KnapSackProblemRecursive.js"></script>
99
</body>
1010
</html>
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
function knapSack(capacity, weights, values, n) {
2+
3+
if (n == 0 || capacity == 0){
4+
return 0;
5+
}
6+
7+
if (weights[n-1] > capacity){
8+
return knapSack(capacity, weights, values, n-1);
9+
10+
} else {
11+
var a = values[n-1] + knapSack(capacity-weights[n-1], weights, values, n-1),
12+
b = knapSack(capacity, weights, values, n-1);
13+
return (a > b) ? a : b;
14+
}
15+
}
16+
17+
var values = [3,4,5],
18+
weights = [2,3,4],
19+
capacity = 5,
20+
n = values.length;
21+
22+
console.log(knapSack(capacity, weights, values, n));

0 commit comments

Comments
 (0)