# [509\. Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) :::spoiler Solution - Recursion ```cpp= class Solution { public: int fib(int n) { if(n < 2) return n; return fib(n - 1) + fib(n - 2); } }; ``` - T: $O(2^N)$ - S: $O(N)$ ::: :::spoiler Solution - DP ```cpp= class Solution { public: int fib(int n) { if(n < 2) return n; vector<int> dp(n + 1); dp[0] = 0, dp[1] = 1; for(int i = 2; i < n + 1; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; } }; ``` - T: $O(N)$ - S: $O(N)$ ::: :::spoiler Solution DP improved ```cpp= class Solution { public: int fib(int n) { if(n < 2) return n; int first = 1, second = 1; for(int i = 2; i < n; i++) { int temp = first; first = first + second; second = temp; } return first; } }; ``` - T: $O(N)$ - S: $O(1)$ :::
×
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