https://leetcode.com/problems/coin-change/
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Why not trying to take largest coin not work?
count example: [1, 4, 5], 8
Taking coin 5 and then 1, 1, 1 becomes 4 times.
But taking 4 and 4 becomes 2 times.
NOT_FOUND = 10**4
class Solution:
def coinChange(self, coins, amount: int) -> int:
def f(amount, m):
if amount in m: return m[amount]
if amount == 0: return 0
if amount < 0: return NOT_FOUND
candidates = [1 + f(amount - c, m) for c in coins]
ans = min(candidates)
m[amount] = ans
#print ('amount', amount, 'ans', ans, 'm', m)
return ans
ans = f(amount, {})
if ans >= NOT_FOUND:
ans = -1
return ans