Algorithm/๋™์ ๊ณ„ํš๋ฒ•

[Dynamic Programming] ๋™์ „๋ฐ”๊พธ๊ธฐ - ์ดˆ๊ธ‰

ํด๋กœ์ด๐Ÿ“ 2023. 10. 20. 16:48
์œ ํŠญ ๋งใ…‹

 

 

๐Ÿ“‹ 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]

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด