일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Convert Sorted List to Binary Search Tree
- Regular Expression
- LeetCode
- 운영체제
- 43. Multiply Strings
- Generator
- Python Code
- 715. Range Module
- Class
- Python
- iterator
- shiba
- 컴퓨터의 구조
- 30. Substring with Concatenation of All Words
- kaggle
- Protocol
- 109. Convert Sorted List to Binary Search Tree
- 프로그래머스
- 밴픽
- Python Implementation
- 시바견
- Substring with Concatenation of All Words
- concurrency
- t1
- Decorator
- 파이썬
- DWG
- data science
- attribute
- 315. Count of Smaller Numbers After Self
Archives
- Today
- Total
Scribbling
LeetCode: 322. Coin Change 본문
This is a typical DP problem.
At first, one should think of backtracking all the cases.
That way, you can find the solution but it isn't efficient.
In the meantime, you should notice that you will calculate for the same amount repeatedly when backtracking all the cases.
Inspired by that idea, apply DP there.
Below is the code.
INF = int(1e9)
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
self.dp = {}
if self.dfs(coins, amount) == INF:
return -1
return self.dfs(coins, amount)
def dfs(self, coins, amount):
if amount == 0:
return 0
if amount in self.dp:
return self.dp[amount]
ret = INF
for coin in coins:
if amount - coin >= 0:
ret = min(ret, self.dfs(coins, amount-coin) + 1)
self.dp[amount] = ret
return ret
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(1, amount+1):
for coin in coins:
if coin <= i:
dp[i] = min(dp[i], dp[i-coin]+1)
return dp[-1] if dp[-1] != float('inf') else -1
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 329. Longest Increasing Path in a Matrix (0) | 2022.01.11 |
---|---|
LeetCode: 350. Intersection of Two Arrays II (0) | 2022.01.10 |
LeetCode: 21. Merge Two Sorted Lists (0) | 2022.01.05 |
LeetCode: 442. Find All Duplicates in an Array (0) | 2022.01.05 |
LeetCode: 268. Missing Number (0) | 2022.01.04 |