Skip to content

Commit d63b4b7

Browse files
committed
add solution: coin-change
1 parent 5e4ec0b commit d63b4b7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

β€Žcoin-change/ZetBe.pyβ€Ž

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'''
2+
문제: μ£Όμ–΄μ§„ 동전 μ’…λ₯˜λ‘œ νŠΉμ • κΈˆμ•‘μ„ λ§Œλ“€κΈ° μœ„ν•œ μ΅œμ†Œ 동전 개수λ₯Ό κ΅¬ν•˜μ‹œμ˜€.
3+
풀이: 동적 κ³„νšλ²•(DP)을 μ‚¬μš©ν•˜μ—¬ 각 κΈˆμ•‘μ— λŒ€ν•΄ μ΅œμ†Œ 동전 개수λ₯Ό κ³„μ‚°ν•©λ‹ˆλ‹€. λ§Œμ•½ νŠΉμ • κΈˆμ•‘μ„ λ§Œλ“€ 수 μ—†λ‹€λ©΄ -1을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
4+
μ‹œκ°„ λ³΅μž‘λ„: O(n * m), n은 κΈˆμ•‘(amount), m은 동전 μ’…λ₯˜μ˜ κ°œμˆ˜μž…λ‹ˆλ‹€. 각 κΈˆμ•‘μ— λŒ€ν•΄ λͺ¨λ“  동전을 ν™•μΈν•˜λ―€λ‘œ 전체 μ‹œκ°„ λ³΅μž‘λ„λŠ” O(n * m)μž…λ‹ˆλ‹€.
5+
곡간 λ³΅μž‘λ„: O(n), κΈˆμ•‘(amount)κΉŒμ§€μ˜ μ΅œμ†Œ 동전 개수λ₯Ό μ €μž₯ν•˜λŠ” DP 배열을 μ‚¬μš©ν•˜λ―€λ‘œ 곡간 λ³΅μž‘λ„λŠ” O(n)μž…λ‹ˆλ‹€.
6+
μ‚¬μš©ν•œ 자료ꡬ쑰: λ°°μ—΄(DP λ°°μ—΄)
7+
'''
8+
9+
10+
class Solution:
11+
def coinChange(self, coins: List[int], amount: int) -> int:
12+
if amount == 0:
13+
return 0
14+
if len(coins) == 1 and coins[0] > amount:
15+
return -1
16+
if amount in coins:
17+
return 1
18+
19+
dp = [0 for i in range(amount+1)]
20+
21+
for i in range(amount+1):
22+
for j in range(len(coins)):
23+
if i == 0 and coins[j] < amount:
24+
dp[coins[j]] = 1
25+
elif i > 0 and 0 <= i+coins[j] <= amount:
26+
if dp[i] > 0 and dp[i+coins[j]] > 0:
27+
dp[i+coins[j]] = min(dp[i+coins[j]], dp[i]+1)
28+
elif dp[i] > 0 and dp[i+coins[j]] == 0:
29+
dp[i+coins[j]] = dp[i]+1
30+
31+
32+
33+
34+
if dp[amount] == 0:
35+
return -1
36+
return dp[amount]
37+
38+

0 commit comments

Comments
Β (0)