Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$


Solution (DP)

# ๋งค๋ฒˆ 1๊ณ„๋‹จ, 2๊ณ„๋‹จ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ์Œ
# ์ •์ƒ๊นŒ์ง€ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์€ ๋ช‡ ๊ฐ€์ง€์ธ์ง€ ๊ตฌํ•˜์ž!
class Solution:
    # DP ๋ฐฉ์‹
    # ์‹œ๊ฐ„ ๋ณต์žก๋„: O(N)
    # Runtime: 31ms
    # Beats: 66.32%
    def climbStairs(self, n: int) -> int:
        # ์‹ค์ œ๋กœ n์„ 1, 2, 3, 4, 5 ์ญ‰ ์ ๊ณ  ํ•˜๋‚˜์”ฉ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์„ธ๋ณด์ž
        # 1: 1, 2: 2, 3: 3(2 + 1), 4: 5(2 + 3), 5: 8(3 + 5)
        # ๊ทธ๋Ÿผ ์œ„์™€ ๊ฐ™์ด ๋ฌด์–ธ๊ฐ€์˜ ๊ทœ์น™์ด ์ƒ๊น€ -> ์ด๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด dp์˜ "์ ํ™”์‹"์œผ๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ์Œ
        # f(n) = f(n - 1) + f(n - 2)

        # ์ฒซ๋ฒˆ์งธ ๊ณ„๋‹จ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜์™€ ๋‘๋ฒˆ์งธ ๊ณ„๋‹จ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋”•์…”๋„ˆ๋ฆฌ์— ์ €์žฅ (์ ํ™”์‹์œผ๋กœ ์จ์ค˜์•ผ ํ•˜๋‹ˆ 2๊ฐœ)
        f = dict()
        f[1] = 1
        f[2] = 2

        # ์ ํ™”์‹์—์„œ for๋ฌธ์€ ๋ณดํ†ต 3๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๊ณ  n๊นŒ์ง€์˜ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋งŒ๋“ค์–ด์คŒ
        # 3๋ฒˆ์งธ ๊ณ„๋‹จ๋ถ€ํ„ฐ ์ถœ๋ฐœํ•˜๊ณ , ์ ํ™”์‹์ด n - 2๋ถ€ํ„ฐ n๊นŒ์ง€๋‹ˆ๊นŒ
        for i in range(3, n + 1):
            f[i] = f[i - 1] + f[i - 2]

        return f[n]

Solution (Memorization)

class Solution:
    # Memorization ๋ฐฉ์‹ (dp์ฒ˜๋Ÿผ ๋ชจ๋“  ๊ณ„๋‹จ์˜ ์ˆ˜๋ฅผ ๋‹ค ๊ตฌํ•  ํ•„์š”๊ฐ€ ์‚ฌ์‹ค ์—†์Œ)
    # ๊ทธ๋‹ˆ๊นŒ dp ๋ฐฉ์‹์—์„œ๋Š” for๋ฌธ์œผ๋กœ ์ „์ฒด์˜ ๊ณ„๋‹จ์„ ๋‹ค ๋ˆ ๋‹ค์Œ์— ๊ฒฐ์ •์„ ํ•˜๋‹ˆ๊นŒ
    # ์ด ๋ฐฉ์‹์—์„œ๋Š” ๋ฐฉ๋ฒ• ์ˆ˜๊ฐ€ ๊ตฌํ•ด์ง€๋ฉด ๊ทธ ์œ„์— ์žˆ๋Š” ๊ณ„๋‹จ์„ ๊ณ„์‚ฐํ•  ํ•„์š”๊ฐ€ ์—†๋Š” ๊ฑฐ์ง€
    # ์‹œ๊ฐ„ ๋ณต์žก๋„: O(N)
    # Runtime: 31ms
    # Beats: 66.32%
    def climbStairs(self, n: int) -> int:
        # n์ด 1๊ณผ 2์ผ ๋•Œ๋Š” ์•„๋ž˜์˜ n - 2 ๊ฐ’์ด ์Œ์ˆ˜๊ฐ€ ๋˜๋ฏ€๋กœ ์ž…๋ ฅํ•œ n์ด ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜๋˜๋„๋ก ์ฒ˜๋ฆฌ
        if n < 3:
            return n

        # ์ด์ „๊ณผ ํ˜„์žฌ๋ฅผ ๊ฐ๊ฐ ์ฒซ๋ฒˆ์งธ, ๋‘๋ฒˆ์งธ ๊ณ„๋‹จ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๋กœ ์ €์žฅ
        before, current = 1, 2

        # ์„ธ๋ฒˆ์งธ ๊ณ„๋‹จ๋ถ€ํ„ฐ ๊ตฌํ•˜๋Š” ๋กœ์ง
        # Memorization์„ ์ง„ํ–‰ํ•˜์—ฌ ํ˜„์žฌ์™€ ์ด์ „ ๋ณ€์ˆ˜๋งŒ ๊ณ„์† ์ €์žฅํ•˜์—ฌ ๋Œ๋ ค์ฃผ๋Š” ๊ฑฐ์ง€
        # ๊ทธ๋ž˜์„œ n - 2๋ฒˆ์งธ๊นŒ์ง€ ๋Œ์•„์ฃผ๋Š” ๊ฑฐ๊ณ 
        for _ in range(n - 2):
            # ์ด๋ ‡๊ฒŒ ํ•œ๋ฒˆ์— ์ž‘์„ฑํ•˜์ง€ ์•Š์œผ๋ฉด ์™„์ „ ๋‹ค๋ฅธ ๋กœ์ง์ž„
            # ๋งŒ์•ฝ ์•„๋ž˜ ์ฒ˜๋Ÿผ ์ž‘์„ฑํ•œ๋‹ค๋ฉด
            # before = current
            # current = before + current
            # before์ด current ๋ณ€์ˆ˜๋กœ ์ €์žฅ์ด ๋œ ํ›„, current์— ๋˜ ์ €์žฅ์„ ํ•˜๊ฒŒ ๋˜๋Š” ๊ฑฐ๋‹ˆ๊นŒ
            # ์™„์ „ํžˆ ์ž˜๋ชป๋œ ๋กœ์ง์œผ๋กœ ๋ฐ”๋€œ
            before, current = current, before + current

        return current

Leave a comment