File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ from collections import deque
2+
3+ class Solution :
4+ def coinChange (self , coins : List [int ], amount : int ) -> int :
5+ # dp[i]: amount๊ฐ i์ผ ๋ ์ต์ ๋์ ์ฌ์ฉ ํ์
6+ # ๋ชจ๋ ๊ฒฝ์ฐ ๋ฐฉ๋ฒ์ด ์๋ค๊ณ ๊ฐ์ ํ๊ณ -1๋ก ์ด๊ธฐํ
7+ dp = [- 1 for _ in range (amount + 1 )]
8+
9+ # bfs ์
์
- ํฉ์ด 0์ธ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ณ , ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
10+ dp [0 ] = 0
11+ q = deque ([[0 , 0 ]])
12+
13+ while q :
14+ # ํ์ฌ ๋
ธ๋์ ์ฌ์ฉ ํ์์ ํฉ
15+ current = q .popleft ()
16+
17+ # ๊ฐ๊ฐ์ ๋์ ์ ๋ฌดํํ ์ฌ์ฉํ ์ ์์ผ๋ฏ๋ก, ๊ฐ๋ฅํ ๊ฒฝ์ฐ ๋ชจ๋ ํ์
18+ for coin in coins :
19+ estimated = current [1 ] + coin
20+
21+ # ํ์ฌ ๋
ธ๋์ ํฉ + ๋์ ์ ๊ฐ์น๊ฐ amount๋ฅผ ์ด๊ณผํ ๊ฒฝ์ฐ ์คํต (์๋ฏธ์๋ ์ฐ์ฐ)
22+ # bfs์ ํ์ ๋ฐฉ์์ ๋ฐ๋ผ, ์ ์ ํ์๋ก ๋ชฉํ ๊ฐ๊ฒฉ์ ๋๋ฌํ๋ค๋ฉด ์ด๊ฒ์ด ๋ ์ต์ ์ ๊ฒฐ๊ณผ์ด๋ฏ๋ก ์คํต
23+ # ๋ ์กฐ๊ฑด ๋ชจ๋ ํต๊ณผํ๋ค๋ฉด ํ์ ๋ฃ์ด์ ๋ค์ ํ์
24+ if estimated <= amount and dp [estimated ] == - 1 :
25+ used = current [0 ] + 1
26+ dp [estimated ] = used
27+
28+ new = [used , estimated ]
29+ q .append (new )
30+
31+ # dp[amount]๊ฐ -1์ด๋ฉด ๋ชจ๋ ๊ฒฝ์ฐ ๋ฐฉ๋ฒ์ด ์๋ค๋ ์๋ฏธ์ด๋ฏ๋ก -1 ๋ฐํ
32+ # ๊ทธ๋ ์ง ์๋ค๋ฉด dp[amount] ๋ฐํ
33+ return dp [amount ]
You canโt perform that action at this time.
0 commit comments