--- tags: leetcode --- # [509. Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) --- # My Solution ## Solution 1 ### The Key Idea for Solving This Coding Question Brute Force ### C++ Code ```cpp= class Solution { public: int fib(int n) { if (n == 0 || n == 1) { return n; } return fib(n - 1) + fib(n - 2); } }; ``` ### Time Complexity $O(2^{n})$ ### Space Complexity $O(n)$ ## Solution 2 ### The Key Idea for Solving This Coding Question Top-down DP (memoization) ### C++ Code ```cpp= class Solution { public: int fib(int n) { if (n == 0 || n == 1) { return n; } if (memo.find(n) == memo.end()) { memo[n] = fib(n - 1) + fib(n - 2); return memo[n]; } return memo[n]; } private: unordered_map<int, int> memo; }; ``` ### Time Complexity $O(n)$ ### Space Complexity $O(n)$ ## Solution 3 ### The Key Idea for Solving This Coding Question Bottom-up DP (tabulation) ### C++ Code ```cpp= class Solution { public: int fib(int n) { vector<int> f(n + 1); f[0] = 0; if (n == 0) { return f[0]; } f[1] = 1; if (n == 1) { return f[1]; } for (int i = 2; i <= n; ++i) { f[i] = f[i - 1] + f[i - 2]; } return f[n]; } }; ``` ### Time Complexity $O(n)$ ### Space Complexity $O(n)$ ## Solution 4 ### The Key Idea for Solving This Coding Question Bottom-up DP (iteration) ### C++ Code ```cpp= class Solution { public: int fib(int n) { if (n == 0 || n == 1) { return n; } int a = 0, b = 1, c; for (int i = 2; i <= n; ++i) { c = a + b; a = b; b = c; } return c; } }; ``` ### Time Complexity $O(n)$ ### Space Complexity $O(1)$ # Miscellane <!-- # Test Cases ``` 0 ``` ``` 1 ``` ``` 2 ``` ``` 3 ``` ``` 4 ``` ``` 5 ``` ``` 6 ``` ``` 7 ``` ``` 8 ``` ``` 9 ``` ``` 10 ``` ``` 11 ``` ``` 12 ``` ``` 13 ``` ``` 14 ``` ``` 15 ``` ``` 16 ``` ``` 17 ``` ``` 18 ``` ``` 19 ``` ``` 20 ``` ``` 21 ``` ``` 22 ``` ``` 23 ``` ``` 24 ``` ``` 25 ``` ``` 26 ``` ``` 27 ``` ``` 28 ``` ``` 29 ``` ``` 30 ``` -->
×
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