# Leetcode 509. Fibonacci Number ## 題解 ### DP 自底向上 (bottom up) ```python! class Solution: def fib(self, n: int) -> int: # DP bottom up # Time complexity: O(n) # Space complexity: O(1) if n == 0: return 0 n1 = 1 # 0(n1) + 1(n2) -> 原本的 n2 取代 n1 所以從 2 開始 n1 為 1 n2 = 1 # 0 + 1 => 1 (n1 + n2) 下一個狀態 # 決策樹 # (n1) 0 + (n2) 1 => (n1) 1 + (n2) 1 # (next) 1 (next) 2 for i in range(2,n): temp = n2 # 先把 n2 記下來,因為等下要先替換 n2 = next n2 = n1 + n2 # 替換 n2 n1 = temp # 把原本的 n2 替換成 n1 return n2 ``` ### 遞迴 ```python! class Solution: def fib(self, n: int) -> int: if n == 0: return 0 if n <= 2: return 1 return self.fib(n - 1) + self.fib(n - 2) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up