Skip to content

Instantly share code, notes, and snippets.

@tuantm8
Created May 6, 2017 23:54
Show Gist options
  • Select an option

  • Save tuantm8/165d06ec145e42bb3d111ce75d139385 to your computer and use it in GitHub Desktop.

Select an option

Save tuantm8/165d06ec145e42bb3d111ce75d139385 to your computer and use it in GitHub Desktop.
Coin Change Problem hackerrank
def getWays(n, c):
# Complete this function
m = len(c)
# table will contains "cache"
# table[i, j] ~ change number i by first j coins (coins array should be sorted firstly)
table = [ [0 for j in range(m)] for i in range(n + 1) ]
for i in range(n+1):
for j in range(m):
if i == 0:
# change 0 with any coins --> 1
table[i][j] = 1
elif j == 0:
# only one coin
if i % c[j]:
# no way to change if the number is not multiple of current (sole) coin
table[i][j] = 0
else:
# only one way if the number if the multiple of current coin
table[i][j] = 1
elif i < c[j]:
# the number to change is smaller than current coin, no luck for it :)
# it gets the ways with only coins smaller than it
table[i][j] = table[i][j - 1]
else:
# others = summary of number of ways to change without a coin and number of ways to change with a least one of that coin
table[i][j] = table[i - c[j]][j] + table[i][j - 1]
return table[n][m - 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment