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

[Dynamic Programming] ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ - ์ดˆ๊ธ‰

ํด๋กœ์ด๐Ÿ“ 2023. 10. 20. 12:28

โ†’

 

๐Ÿ“‹ LeetCode 70๋ฒˆ

 

Climbing Stairs - LeetCode

Can you solve this real interview question? Climbing Stairs - You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?   Example 1: Input: n = 2 Outpu

leetcode.com

 

์˜ฌ๋ผ๊ฐ€์•ผ ํ•˜๋Š” ๊ณ„๋‹จ์˜ ์ˆ˜: n

n์œผ๋กœ ์˜ฌ๋ผ๊ฐ€๊ธฐ ์œ„ํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” n-1์—์„œ 1์นธ or n-2์—์„œ 2์นธ ์˜ฌ๋ผ ๊ฐ€๋Š” ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.

-> ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์™€ ๊ฐ™๋‹ค!

 

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป ๋‚ด ํ’€์ด

class Solution:
    def climbStairs(self, n: int) -> int:
        if n == 1:
            return 1
        
        fibo = [1,2]
        for i in range(2,n):
            fibo.append(fibo[i-1]+fibo[i-2])
        
        return fibo[-1]

 

 

 

๐Ÿ“‹ LeetCode 746๋ฒˆ

 

Min Cost Climbing Stairs - LeetCode

Can you solve this real interview question? Min Cost Climbing Stairs - You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the ste

leetcode.com

์˜ฌ๋ผ๊ฐ€๋Š”๋ฐ ์ธ๋ฑ์Šค ๋งˆ๋‹ค ๊ฐ๊ฐ arr = [ 1, 2, 4, 6, 2, 4, 6, 1 ]์˜ ๋น„์šฉ์ด ๋“œ๋Š” ๊ณ„๋‹จ์ด ์žˆ๋‹ค.

๊ณ„๋‹จ์€ 1์นธ or 2์นธ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค.

 

F(0)์œผ๋กœ ์˜ฌ๋ผ๊ฐ€๋Š”๋ฐ ๋“œ๋Š” ๋น„์šฉ์€ 0

F(1)์œผ๋กœ ์˜ฌ๋ผ๊ฐ€๋Š”๋ฐ ๋“œ๋Š” ๋น„์šฉ๋„ 0

 

F(2)์œผ๋กœ ์˜ฌ๋ผ๊ฐ€๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” F(0)์—์„œ 2์นธ ์˜ฌ๋ผ๊ฐ€๊ธฐ or F(1)์—์„œ 1์นธ ์˜ฌ๋ผ๊ฐ€๊ธฐ

โ†’ arr[0],arr[1]์˜ ์ตœ์†Ÿ๊ฐ’ : min(F(0)+1,F(1)+2) = 1

 

F(3)์œผ๋กœ ์˜ฌ๋ผ๊ฐ€๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” F(1)์—์„œ 2์นธ ์˜ฌ๋ผ๊ฐ€๊ธฐ or F(2)์—์„œ 1์นธ ์˜ฌ๋ผ๊ฐ€๊ธฐ

โ†’ arr[1], arr[2]์˜ ์ตœ์†Ÿ๊ฐ’ : min(F(1)+arr[1], F(2)+arr[2]) = min(0+2, 1+4) = 2

.

.

 

F(n)=min(F(nโˆ’2)+cost(nโˆ’2),F(nโˆ’1)+cost(nโˆ’1))

 

์‹œ๊ฐ„ ๋ณต์žก๋„ : O(n)

๊ณต๊ฐ„ ๋ณต์žก๋„ : O(n) โ†’ ์‚ฌ์‹ค์ƒ ์ €์žฅํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ๊ณต๊ฐ„์€ 2์นธ์ด๋ฏ€๋กœ O(1)๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

 

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป ๋‚ด ํ’€์ด

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        arr=[0,0]
        for i in range(2,len(cost)+1):
            # print(f'{i}๋ฒˆ์งธ {arr[i-2]+cost[i-2]} {arr[i-1]+cost[i-1]}')
            arr.append(min(arr[i-2]+cost[i-2], arr[i-1]+cost[i-1]))
        return arr[-1]