Given an infinite number of different coin types (such as pennies, nickels, dimes, quarters) find out how many ways n cents can be represented.
My code appears to work (although I am curious to know if it has any correctness issue). But I feel like the memoization I am doing is a bit inelegant. Can we do without dictionaries/maps, perhaps a dynamic programming based approach using 2d arrays? Or is that even worse in terms of time and space complexity?
Also is my code to update the memoized_sol good in terms of coding technique?
''' Parameters: cents: amount to get change for. coin_vals: list of coin denominations in no particular order. Returns: number of ways <cents> can be changes using any number of coins from the given list ''' def get_coin_change_count (cents, coin_vals): memoized_sol = {} return compute_coin_change_count(cents, coin_vals, 0, memoized_sol ) def compute_coin_change_count (rem_cents, coin_vals, coin_index, memoized_sol ): if coin_index in memoized_sol: if rem_cents in memoized_sol[coin_index]: return memoized_sol[coin_index][rem_cents] else: memoized_sol[coin_index] = {} if rem_cents == 0: return 1 if coin_index >= len(coin_vals): return 0 coin_val = coin_vals[coin_index] i = 0 count = 0 while i*coin_val <= rem_cents: count = count + compute_coin_change_count\ ( rem_cents - i*coin_val, coin_vals, coin_index+1, memoized_sol ) i = i + 1 memoized_sol[coin_index][rem_cents] = count return count w = get_coin_change_count ( 37, [10, 1, 5, 25]) print (w)
functools.lru_cache(None). \$\endgroup\$