def knapsack_recursive(weights, values, capacity, n, memo):
"""
Recursive solution for the 0/1 Knapsack problem with memoization.
Parameters:
weights (list[int]): Item weights.
values (list[int]): Item values.
capacity (int): Remaining capacity of the knapsack.
n (int): Number of items left to consider.
memo (dict): Cache for memoization (key: (n, capacity)).
Returns:
int: Maximum total value for the given parameters.
"""
if n == 0 or capacity == 0:
return 0
if (n, capacity) in memo:
return memo[(n, capacity)]
if weights[n - 1] > capacity:
result = knapsack_recursive(weights, values, capacity, n - 1, memo)
else:
include = values[n - 1] + knapsack_recursive(weights, values, capacity - weights[n - 1], n - 1, memo)
exclude = knapsack_recursive(weights, values, capacity, n - 1, memo)
result = max(include, exclude)
memo[(n, capacity)] = result
return result
if __name__ == "__main__":
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
n = len(values)
memo = {}
max_value = knapsack_recursive(weights, values, capacity, n, memo)
print( memo )
print(f"Maximum value in knapsack = {max_value}")