diff --git a/src/dsa/caching_memoization.py b/src/dsa/caching_memoization.py index 20390ec..f67c254 100644 --- a/src/dsa/caching_memoization.py +++ b/src/dsa/caching_memoization.py @@ -69,14 +69,23 @@ def binomial_coefficient(n: int, k: int) -> int: def coin_change(coins: list[int], amount: int, index: int) -> int: - if amount == 0: - return 1 - if amount < 0 or index >= len(coins): - return 0 + memo: dict[tuple[int, int], int] = {} - return coin_change(coins, amount - coins[index], index) + coin_change( - coins, amount, index + 1 - ) + def dp(amount: int, index: int) -> int: + if amount == 0: + return 1 + if amount < 0 or index >= len(coins): + return 0 + + key = (amount, index) + if key in memo: + return memo[key] + + result = dp(amount - coins[index], index) + dp(amount, index + 1) + memo[key] = result + return result + + return dp(amount, index) def knapsack(weights: list[int], values: list[int], capacity: int, n: int) -> int: @@ -89,4 +98,4 @@ def knapsack(weights: list[int], values: list[int], capacity: int, n: int) -> in return max( values[n - 1] + knapsack(weights, values, capacity - weights[n - 1], n - 1), knapsack(weights, values, capacity, n - 1), - ) \ No newline at end of file + )