Created
December 30, 2018 18:09
-
-
Save avinashselvam/cb7eb0001a26049b9f04ce3227866a2b to your computer and use it in GitHub Desktop.
function to calculate coin change recursively using dynamic programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
n = 10 | |
c = [2, 3, 5, 6] | |
ways = [[0 if i < min(c) else - 1 for i in range(n + 1)] for j in c] | |
def num_ways(n, c): | |
row = len(c) - 1 | |
# base case | |
if n < min(c): return 0 | |
# if not pre calculated | |
if ways[row][n] == -1: | |
if n in c: ways[row][n] = 1 | |
else: ways[row][n] = 0 | |
for i in range(len(c)): | |
ways[row][n] += num_ways(n - c[i], c[i:]) | |
return ways[row][n] | |
num_ways(n+1, c) | |
print(ways[len(c)-1][n]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment