๐ LeetCode 322๋ฒ
Coin Change - LeetCode
Can you solve this real interview question? Coin Change - You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make
leetcode.com
F(n)์ด ํฉํด์ n์ด ๋๋ coins์ ํฉ์ด๋ผ๊ณ ์ ํด์ค๋ค.
F(11)์ด ๋๋ ๊ฒฝ์ฐ์ ์๋ ( F(11-1) or F(11-2) or F(11-5) ) ๊ทธ๋ฆฌ๊ณ ์ ๊ฒฝ์ฐ์ ์์์ ๋์ ํ๋๋ฅผ ๋ํ ๊ฐ์ด๊ธฐ ๋๋ฌธ์ + 1๋ ํด์ค๋ค.
$$ F(n) = min( F(n-1), F(n-2), F(n-5) ) + 1 $$
๋ง์ฝ F(1)๊ณผ ๊ฐ์ด ์ฃผ์ด์ง coin๋ค๋ก ๊ตฌ์ฑํ ์ ์๋ ์๊ฐ ๋์ค๋ฉด F์ ๊ฐ์ ์ ์ฅํด๋ array์ -1 ์ ๋ฃ์ด์ค๋ค.
min์ ๊ฐ์ ๋น๊ตํ ๋, ํด๋น ๊ฐ์ด -1์ธ์ง ํ์ธํด์ค๋ค.
๐ฉ๐ป๐ป ๋ด ํ์ด
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
arr = [0]
# amount๊ฐ 0์ด๋ผ๋ฉด ๊ณ์ฐํ ํ์ ์์ผ๋๊น ๋ฐ๋ก return
if amount == 0:
return 0
for i in range(1,amount+1):
min_i = []
# ๊ฐ๊ณ ์๋ coin ๋ณ๋ก ๊ณ์ฐํด์ค๋ค..
for j in range(len(coins)):
if i-coins[j] < 0:
# ๊ตฌํด์ผํ๋ ์๊ฐ coin ๊ฐ๋ณด๋ค ์์ผ๋ฉด ํจ์ค
continue
elif i-coins[j] >= 0:
# ์ฝ์ธ๋ณด๋ค ํฌ๋ค๋ฉด arr ๊ฒ์ฌ
if arr[i-coins[j]] == -1:
continue
else:
# ์ ์ฅํ arr์ ๊ฐ์ด -1์ด ์๋๋ผ๋ฉด + 1
min_i.append(arr[i-coins[j]]+1)
if len(min_i)<1:
# ์ ์ฅํ ๊ฒ ์๋ค๋ฉด -1
arr.append(-1)
else:
# if๋ ์ฝ๋ ์์ ํ๋ค๊ฐ ๋ชป์ง์ด ๋ถ๋ถ์ธ๋ฐ ํ์ ์์๋ฏ?
if min(min_i) == -1:
arr.append(-1)
else:
# ์ ์ฅํ ๊ฐ๋ค ์ค ์ต์๊ฐ
arr.append(min(min_i))
return arr[-1]
๋ค๋ฅธ ์ฌ๋์ ํ์ด
'Algorithm > ๋์ ๊ณํ๋ฒ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Dynamic Programming] ์ต์ ๋น์ฉ ๊ตฌํ๊ธฐ - ์ด๊ธ (0) | 2023.10.20 |
---|---|
[Dynamic Programming] ๊ณ๋จ ์ค๋ฅด๊ธฐ - ์ด๊ธ (0) | 2023.10.20 |
[Dynamic Programming] ๋ค์ด๋๋ฏน ํ๋ก๊ทธ๋๋ฐ์ ๊ธฐ์ด (0) | 2023.10.20 |