File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
You canโt perform that action at this time.
0 commit comments