Recently looking at the algorithm of books, see a very old question-Fibonacci series, this topic in the university must have contacted, we still in the exam, but only confined to the content of the textbook at that time, and did not carefully consider the implementation of this topic, today to a small inquiry
The most common implementation algorithm is recursion, this problem is also a very basic example of recursive algorithm implementation;
The following is the method of finding the first n elements of the Fibonacci sequence in Java code to implement recursion:
Public Static Long FibonacciDemo1 (long N) { ifreturn 0; if return 1; return FibonacciDemo1 (n-1) + FibonacciDemo1 (n-2);}
The recursive method implementation is the most concise, but not the best, because the request for the nth element of the data, first n-1 and n-2, in the same way to seek F (n-2) +f (n-3) and F (n-3) +f (n-4), there will be a large number of redundant computation;
For example, requiring the value of f (10) to be calculated separately is as follows:
At the same time as n increases, the computation time increases exponentially and the time complexity is O (2^n) .
In order to solve this problem, improve the computational efficiency, can be modified as a method
Public Static LongFibonacciDemo2 (LongN) {if(n <= 0)return0; LongElement1 = 1; LongElement2 = 0; Longresult = 0; for(inti = 0; I < n; i++) {result= Element1 +Element2; Element1=Element2; Element2=result; } returnresult;}
Although the recursive method is no longer used, and the code looks more bloated, but when n tends to be large, the operation efficiency is much higher than the recursive method, the time complexity isO (n)
In the interview, perhaps the interviewer does not require the use of recursion to implement some algorithms, and our common methods may imprison our thinking, sometimes the more common method, can play a different role; but that's not the answer.
Let's discuss an algorithm solution with time complexity O (LOGN)
The implementation algorithm of Fibonacci sequence