I know there are many threads about this challenge, but before marking as duplicate, please read on.
Need to find all the different ways to make change, given a list of coins. I wrote a solution with recursion that works, but is very inefficient. I want to add memoization. I know there are other approaches (e..g here) to solve it, but for my understanding of how things work, I'm seeking your help fixing the problem I found with my solution.
First, here is the code:
d = {}
def make_change(n, coins):
print n
# base case
if n < 0:
print 'Nope'
print '_'*40
return 0
if n == 0:
print 'yay'
print '_'*40
return 1
if n in d:
return d[n]
else:
c = 0
for i in coins:
print 'i = ', i
c += make_change(n-i, [c for c in coins if c<=i]) # https://stackoverflow.com/a/33425875/5056689
d[n] = c
return c
make_change(20, [5,10])
This returns 2 solutions, and the print statements show that the solutions are (5,5,5,5) and (10,10). The third possible solution (10,5,5) isn't included, because 10 is already in the keys.
So, how do I keep a dict with the number of unique ways to get to a certain target, without actually keeping track of all solutions, which would defeat the purpose.
Appreciate your help.