Coin Change Problem - apply Dynamic Programing on my recursive code

74 Views Asked by At

I am working on the HackerRank Coin Change problem - where you are required to calculate the total number of unique ways to give change for n amount from an infinite number of coins from list c.
I am deliberately trying to solve the problem with recursion (top-down) - and I am not interested in bottom-up suggestions (I have seen many solutions).
The results I am getting are fine for a small number of recursive calls.
Examples:

print(getWays(4, [1,2,3]))
>>> 4
print(getWays(4, [1,2,3,4]))
>>> 5

I am properly handling duplications, due to the visited_dict (i.e. (3,1) and (1,3) will not count as 2 solutions.
The issue is (as expected) when I apply a large coin set, and a larger sum to give change for, the recursive call stack will compute forever.
Example:

print(
  getWays(
    166,
    [5, 37, 8, 39, 33, 17, 22, 32, 13, 7, 10, 35, 40, 2, 43, 49, 46, 19, 41, 1, 12, 11, 28]
  )
) # answer should be: 96190959

This is the code that is working, but has no Dynamic Programing applied:

def getWays(n, c):
    visited_dict = {}
    current_selected_list = []
    c.sort()

    target_count = helper(n, c, visited_dict, current_selected_list)
    return target_count

def helper(desirable_sum, options_list, visited_dict, current_selected_list):
    current_sum = sum(current_selected_list)
    if current_sum == desirable_sum:
        return 1
    elif current_sum > desirable_sum:
        return 0
    else:
        new_count = 0
        for option in options_list:
            new_current_selected_list = current_selected_list.copy()
            new_current_selected_list.append(option)
            new_current_selected_list.sort()
            t = tuple(new_current_selected_list)
            if t not in visited_dict:
                visited_dict[t] = True
                new_count += helper(desirable_sum, options_list, visited_dict, new_current_selected_list)

    return new_count

I know that I should probably be using the visited_dict as the cache to the DP solution, and instead of storing True/False I should put the value I get in a call for that unique sorted coin selection tuple key. (and of course, store it when I get it)

How can I add DP into my solution?

By the way, I spotted a different solution here, but would like to know if mine is not compatible for DP, and if it is, please suggest how to apply it.

Thank you!

0

There are 0 best solutions below