|
| 1 | +# idea: DFS/BFS, DP |
| 2 | + |
| 3 | +from collections import deque |
| 4 | +class Solution: |
| 5 | + def coinChange(self, coins: List[int], amount: int) -> int: |
| 6 | + # Why Greedy is not possiple way? |
| 7 | + # A greedy is only optimal in specific coin systems (e.g., denominations like 1, 5, 10, 25) |
| 8 | + # For arbitrary coin denominations, a greedy approach does not always yield the optimal solution. |
| 9 | + queue = deque([(0,0)]) # (동전갯수, 누적금액) |
| 10 | + while queue: |
| 11 | + count, total = queue.popleft() |
| 12 | + if total == amount: |
| 13 | + return count |
| 14 | + for coin in coins: |
| 15 | + if total + coin <= amount: |
| 16 | + queue.append([count+1, total+ coin]) |
| 17 | + return -1 |
| 18 | + |
| 19 | + # # BFS |
| 20 | + # def coinChange(self, coins: List[int], amount: int) -> int: |
| 21 | + # queue = deque([(0,0)]) # (동전갯수, 누적금액) |
| 22 | + # visited = set() |
| 23 | + # while queue: |
| 24 | + # count, total = queue.popleft() |
| 25 | + # if total == amount: |
| 26 | + # return count |
| 27 | + # if total in visited: |
| 28 | + # continue |
| 29 | + # visited.add(total) |
| 30 | + # for coin in coins: |
| 31 | + # if total + coin <= amount: |
| 32 | + # queue.append([count+1, total+ coin]) |
| 33 | + # return -1 |
| 34 | + |
| 35 | + |
| 36 | + # DP |
| 37 | + # dp[i] = min(dp[i], dp[i-coin]+1) |
| 38 | + # from collections import deque |
| 39 | + # class Solution: |
| 40 | + # def coinChange(self, coins: List[int], amount: int) -> int: |
| 41 | + # dp=[0]+[amount+1]*amount |
| 42 | + # for coin in coins: |
| 43 | + # for i in range(coin, amount+1): |
| 44 | + # dp[i] = min(dp[i], dp[i-coin]+1) |
| 45 | + # return dp[amount] if dp[amount] < amount else -1 |
| 46 | + |
| 47 | + |
0 commit comments