web123456

Total number of coin exchange plans (dynamic planning)

  • import pandas as pd
  • # S = 4
  • # coins = [1, 2, 3] # Assume that they are sorted from small to large
  • S = 10
  • coins = [2, 3, 5, 6]
  • DP = [[0 for x in range(S)] for _ in range(len(coins))]
  • def init():
  • # Initialization of the first line
  • for j in range(S):
  • if (j + 1) % coins[0] == 0: # Here the default coins[0] is the minimum face value
  • DP[0][j] = 1
  • # The first column does not require initialization
  • def dynamic():
  • for j in range(S): # List
  • for i in range(1, len(coins)): # Line, starting from the second line
  • if j + 1 - coins[i] < 0:
  • xx = 0
  • elif j + 1 - coins[i] == 0:
  • xx = 1
  • else:
  • xx = DP[i][j - coins[i]]
  • DP[i][j] = DP[i - 1][j] + xx
  • if __name__ == '__main__':
  • init()
  • dynamic()
  • print((DP))