Link:
https://leetcode.com/problems/coin-change/
My Code:
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
if amount == 0:
return 0
else:
ResultList = [0]
MinCoin = min(coins)
for i in range(1,(amount+1)):
if i < MinCoin:
ResultList.append(0)
else:
AvailableCoinList = []
for j in range(len(coins)):
if coins[j]<=i:
AvailableCoinList.append(coins[j])
Min = 2**31
if i in AvailableCoinList:
ResultList.append(1)
else:
for k in AvailableCoinList:
if ResultList[i-k] != 0:
Min = min(ResultList[i-k],Min)
if Min == 2**31:
ResultList.append(0)
else:
ResultList.append(Min+1)
if ResultList[amount] == 0:
return -1
else:
return ResultList[amount]
Explanation: The code follows this idea: For an amount n, we check all the coins that is smaller than it, for example k_1,…,k_j as j coins that is available. The DP[i] list is the minimum amount of coins that can achieve amount i with given coin List. so We check all the available coin i in the list, then we take the minimum of all n-i. There are several situations: first, if n is in the coin list, then the answer is 1. Next if n is not in the coin list, then if all the previous n-k_j are zero, then it means we cannot get the number here, hence we return 0. Otherwise we take the minimum of all non- zero n- k_j and then take the minimum and plus 1.