The memoized solution to the coin change problem is similar to the recursive solution, except that it checks the cache before computing the subproblems. If the cache contains a valid value for the subproblem, it returns it without further computation. Otherwise, it computes the subproblem recursively and stores the result in the cache for future use.
The memoized solution can be implemented in Python as follows:
# Define the coins and the amount
coins = [1, 2, 5]
amount = 7
# Initialize the cache with -1
cache = [[-1 for _ in range(len(coins))] for _ in range(amount + 1)]
# Define the memoized function
def coin_change_memo(amount, coins, index, cache):
# Base cases
if amount == 0:
return 1
if amount < 0 or index < 0:
return 0
# Check the cache
if cache[amount][index] != -1:
return cache[amount][index]
# Recursive cases
# Use the coin
use = coin_change_memo(amount - coins[index], coins, index, cache)
# Don't use the coin
skip = coin_change_memo(amount, coins, index - 1, cache)
# Store and return the result
cache[amount][index] = use + skip
return cache[amount][index]
# Call the memoized function
print(coin_change_memo(amount, coins, len(coins) - 1, cache))
The memoized solution has a time complexity of O(amount * len(coins)) and a space complexity of O(amount * len(coins)), which are both better than the recursive solution, which has a time complexity of O(2^(amount + len(coins))) and a space complexity of O(amount + len(coins)).