File tree 1 file changed +37
-0
lines changed
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ # BFS -> λ¨Όμ μ°Ύλ ν΄λ΅μ΄ κ°μ₯ μ μ μ°μ°/κ°μ₯ μ§§μ 거리 -> κ°μ₯ μ μ countλΆν° κ³μ°ν΄ μ΅μνμ λμ μ 보μ₯
3
+ # O(amount * n) time, O(amount) space
4
+
5
+ from collections import deque
6
+
7
+ class Solution :
8
+ def coinChange (self , coins : List [int ], amount : int ) -> int :
9
+ queue = deque ([(0 , 0 )]) # (λμ κ°μ, νμ¬ κΈμ‘)
10
+ visited = set ()
11
+ while queue :
12
+ count , total = queue .popleft ()
13
+ if total == amount :
14
+ return count
15
+ if total in visited :
16
+ continue
17
+ visited .add (total )
18
+ for coin in coins :
19
+ if total + coin <= amount :
20
+ queue .append ((count + 1 , total + coin ))
21
+ return - 1
22
+
23
+
24
+ # DP νμ΄
25
+ # μ΄λ€ κΈμ‘μ λ§λλλ° νμν λμ κ°μλ₯Ό μλ©΄, κ·Έ κΈμ‘λ³΄λ€ ν° κΈμ‘μ λ§λλλ° νμν λμ κ°μλ μ μ μλ€.
26
+ # dp[i] = min(dp[i], dp[i - coin] + 1)
27
+ # O(amount * n) time, O(amount) space
28
+
29
+ class Solution :
30
+ def coinChange (self , coins : List [int ], amount : int ) -> int :
31
+ dp = [0 ] + [amount + 1 ] * amount
32
+
33
+ for coin in coins :
34
+ for i in range (coin , amount + 1 ):
35
+ dp [i ] = min (dp [i ], dp [i - coin ] + 1 )
36
+
37
+ return dp [amount ] if dp [amount ] < amount + 1 else - 1
You canβt perform that action at this time.
0 commit comments