Published:
Updated:

  • ๋ฌธ์ œ์— ์ •๋‹ต์ด ๊ฑฐ์˜ ๋‚˜์™€ ์žˆ์–ด์„œ ์ด์ง€์ธ ๋“ฏ


Solution

import collections


class Solution:

    dp = collections.defaultdict(int)

    def fib(self, n: int) -> int:
        # ํ”ผ๋ณด๋‚˜์น˜ ์ •์˜: n >= 2
        if n <= 1:
            return n

        # dp[n]์ด ์กด์žฌํ•  ๋•Œ๋Š” ๊ทธ๋ƒฅ ๋ฆฌํ„ด
        if self.dp[n]:
            return self.dp[n]

        # dp[n]์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฐ’์ด๋ผ๋ฉด
        # ๊ณ„์‚ฐํ•œ ๊ฐ’์„ dp[n]์— ์ €์žฅํ•ด๋‘ 
        self.dp[n] = self.fib(n - 1) + self.fib(n - 2)
        # ๊ทธ๋ฆฌ๊ณ  ๋ฐ”๋กœ ๋ฆฌํ„ด
        return self.dp[n]


Reference

Leave a comment