classSolution: defcoinChange(self, coins, amount): if amount == 0: return0 stat = [0] * (amount + 1) for i in range(amount + 1): for coin in coins: if i - coin > 0and stat[i - coin] > 0: if stat[i] > 0: stat[i] = min(1 + stat[i - coin], stat[i]) else: stat[i] = 1 + stat[i - coin] elif i - coin == 0: stat[i] = 1
return stat[amount] if stat[amount] > 0else-1
Version 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defcoinChange(self, coins, amount): if amount == 0: return0 stat = [0if i notin coins else1for i in range(amount + 1)] for i in range(amount + 1): for coin in coins: if i - coin > 0and stat[i - coin] > 0: if stat[i] > 0: stat[i] = min(1 + stat[i - coin], stat[i]) else: stat[i] = 1 + stat[i - coin]