LeetCode (10) - Coin Change(파이썬, python)

1 분 소요

❓ 문제

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

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

Example 4:

Input: coins = [1], amount = 1
Output: 1

Example 5:

Input: coins = [1], amount = 2
Output: 2

Constraints:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

Given Code

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        

내 풀이

class Solution:
    def coinChange(self, coins: list, amount: int) -> int:
        num = [2**31 - 1] * (amount + 1)
        num[0] = 0

        for coin in coins:
            for i in range(coin, amount + 1):
                num[i] = min(num[i], num[i - coin] + 1)
                # print(coin, i, num[i], num) # 모니터링용
        if num[amount] > amount:
            return -1
        else:
            return num[amount]

잘 모르겠어서 https://velog.io/@bye9/LeetCode%ED%8C%8C%EC%9D%B4%EC%8D%AC-322.-Coin-Change 를 참고했다.

Dynamic Programming을 이용해야하는데 감이 잘 안왔었다… d라는 배열을 만들어 최소 횟수를 체크하는것이 핵심. d[i]는 i원을 만들기 위한 최소 동전의 수 이다!