Repository navigation
Expand file tree
/
Copy pathdynamicProgrammingRecursive.js
More file actions
66 lines (51 loc) · 2.1 KB
/
Copy pathdynamicProgrammingRecursive.js
File metadata and controls
66 lines (51 loc) · 2.1 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
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Recursive Dynamic Programming with memoization for the Knapsack Problem
* Uses a top-down approach with caching
* @param {Array} items - Array of items with value and weight properties
* @param {Number} capacity - Maximum capacity of the knapsack
* @returns {Array} - Selected items that maximize value
*/
function dynamicProgrammingRecursiveKnapsack(items, capacity) {
const n = items.length;
let steps = 0;
// Create a cache object (hashtable) for memoization
// We'll use a string key "i_c" where i is the item index and c is the remaining capacity
const memo = {};
// Define the recursive function with memoization
function knapsackRecursive(i, remainingCapacity) {
steps++;
// Base case: no items left or no capacity
if (i === 0 || remainingCapacity === 0) {
return { value: 0, selected: [] };
}
// Create a key for the memo cache
const key = `${i}_${remainingCapacity}`;
// Check if we've already solved this subproblem (memoization)
if (memo[key]) {
return memo[key];
}
const currentItem = items[i - 1];
// If current item is too heavy, skip it
if (currentItem.weight > remainingCapacity) {
return memo[key] = knapsackRecursive(i - 1, remainingCapacity);
}
// Try two options: include current item or skip it
// Option 1: Skip current item
const skipItem = knapsackRecursive(i - 1, remainingCapacity);
// Option 2: Include current item
const includeItemResult = knapsackRecursive(i - 1, remainingCapacity - currentItem.weight);
const includeItem = {
value: includeItemResult.value + currentItem.value,
selected: [...includeItemResult.selected, currentItem]
};
// Choose the better option
const result = includeItem.value > skipItem.value ? includeItem : skipItem;
// Store the result in the memo cache
memo[key] = result;
return result;
}
// Call the recursive function to solve the problem
const result = knapsackRecursive(n, capacity);
return result.selected;
}
export default dynamicProgrammingRecursiveKnapsack;