Skip to content

Commit 3e8a753

Browse files
committed
feat: Add Coin Change solutions
1 parent a338957 commit 3e8a753

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

โ€Žcoin-change/thispath98.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution:
2+
def coinChange(self, coins: List[int], amount: int) -> int:
3+
"""
4+
Intuition:
5+
dp ๋ฐฐ์—ด์— ์ด์ „ ๊ธˆ์•ก์— ๋Œ€ํ•œ ์ตœ์†Œ ๊ฐœ์ˆ˜๋ฅผ ์ €์žฅํ•ด๋‘๊ณ 
6+
๊ฐฑ์‹ ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ž‘๋™ํ•œ๋‹ค.
7+
8+
for ๋ฃจํ”„๋ฅผ ๋Œ๋ฉด์„œ ํ˜„์žฌ ๊ฐ€๊ฒฉ์—์„œ coin๋งŒํผ์˜ ๊ฐ€๊ฒฉ์„
9+
๋บ์„ ๋•Œ ๊ฑฐ์Šฌ๋Ÿฌ์ค„ ์ˆ˜ ์žˆ๋‹ค๋ฉด, ๊ทธ ๊ฐ’์—์„œ 1๊ฐœ๋ฅผ ๋”ํ•ด์ค€
10+
๊ฐœ์ˆ˜๋ฅผ prev_coins์— ์ €์žฅํ•œ๋‹ค.
11+
12+
์ดํ›„ prev_coins๊ฐ€ ์กด์žฌํ•˜๋ฉด ํ˜„์žฌ ์ธ๋ฑ์Šค์—์„œ ๊ฑฐ์Šฌ๋Ÿฌ์ค„ ์ˆ˜ ์žˆ๋Š”
13+
๋™์ „์˜ ์ตœ์†Œ ๊ฐœ์ˆ˜๋ฅผ ๊ฐฑ์‹ ํ•œ๋‹ค.
14+
15+
Time Complexity:
16+
O(amount x coins.length):
17+
amount ๋งŒํผ ๋ฃจํ”„๋ฅผ ์ˆœํšŒํ•˜๋Š”๋ฐ ๊ฐ ๋ฃจํ”„๋งˆ๋‹ค
18+
coins.length ๋งŒํผ prev_coins ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค.
19+
20+
Space Complexity:
21+
O(amount):
22+
amount๋งŒํผ์˜ ํฌ๊ธฐ๋ฅผ ๊ฐ€์ง€๋Š” dp ๋ฐฐ์—ด์„ ์ €์žฅํ•œ๋‹ค.
23+
"""
24+
dp = [0 for _ in range(amount + 1)]
25+
26+
for coin in coins:
27+
if coin <= amount:
28+
dp[coin] = 1
29+
30+
for i in range(1, amount + 1):
31+
if dp[i]:
32+
continue
33+
34+
prev_coins = [dp[i - coin] + 1 for coin in coins if i >= coin and dp[i - coin] > 0]
35+
if prev_coins:
36+
dp[i] = min(prev_coins)
37+
38+
answer = -1 if amount > 0 and dp[amount] == 0 else dp[amount]
39+
return answer

0 commit comments

Comments
ย (0)