leetcode 322. coin change

wonderful world·2021년 12월 26일
0

leetcode

목록 보기
13/21

https://leetcode.com/problems/coin-change/

Description

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

NOTE

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.

solution: dynamic programming(memoization)

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

Reference

  • Video Label bestSum at 1h52m08s
profile
hello wirld

0개의 댓글