\( F_n = F_{n-1} + F_{n-2} \)
\( F_0 = 0, F_1 = F_2 = 1 \)
Problem
a “toy” problem. It’s easy to understand and maybe surprising that there are many different solutions.
Java
Recursion
1 | class Solution { |
Submission Detail
- 31 / 31 test cases passed.
- Runtime: 14 ms, faster than 5.42% of Java online submissions for Fibonacci Number.
- Memory Usage: 36.1 MB, less than 5.51% of Java online submissions for Fibonacci Number.
Dynamic Programming
Using dynamic programming in the calculation of the nth member of the Fibonacci sequence improves its performance greatly.
bottom-up approach
1
1 | class Solution { |
Submission Detail
- 31 / 31 test cases passed.
- Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number.
- Memory Usage: 35.8 MB, less than 36.87% of Java online submissions for Fibonacci Number.
2
1 | class Solution { |
Submission Detail
- 31 / 31 test cases passed.
- Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number.
- Memory Usage: 36.6 MB, less than 5.51% of Java online submissions for Fibonacci Number.
top-down approach
1
1 | import java.util.HashMap; |
Submission Detail
- 31 / 31 test cases passed.
- Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number.
- Memory Usage: 36 MB, less than 25.69% of Java online submissions for Fibonacci Number.
2
As constraints 0 <= n <= 30
1 | class Solution { |
Submission Detail
- 31 / 31 test cases passed.
- Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number.
- Memory Usage: 35.7 MB, less than 69.84% of Java online submissions for Fibonacci Number.
formula
golden ratio \(\huge \varphi = \frac{1 + \sqrt{5}}{2} \)
\(\LARGE F_n = \frac{\varphi^n-(1-\varphi)^n}{\sqrt{5}} \)
This solution is often used as a standard example of the method of generating functions.
1 | class Solution { |
Submission Detail
- 31 / 31 test cases passed.
- Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number.
- Memory Usage: 36.2 MB, less than 5.51% of Java online submissions for Fibonacci Number.