Sword refers to the offer face question 9 (Java version) Fibonacci series

Source: Internet
Author: User

Topic One: Write a function, enter N, and find the nth term of the Fibonacci sequence. The Fibonacci sequence is defined as follows:


1, inefficient efficiency of the solution, the critical interviewer will not like

A lot of C language textbooks in the narration of recursive functions, all households take Fibonacci as an example, so many candidates for this problem recursive solution are very familiar.

Here is the implementation code


We have repeatedly used this question to explain recursive functions in our textbooks, and it does not explain that recursion is the best solution for this problem. The interviewer will prompt us. The recursive solution has serious efficiency problems that require us to analyze the cause.

We use the solution F (10) as an example to analyze the recursive solution process. To obtain F (10), we need to first find F (9) and F (8). Similarly, F (9) requires that F (8) and F (7) be obtained first. We use trees to construct this dependency relationship. As shown in the figure:


It's not hard to see that there are many nodes in this tree that are duplicated, and that the number of repeated nodes increases dramatically as n increases, which means that the amount of computation increases dramatically as n increases. In fact, the time complexity calculated by the recursive method is incremented by the exponent of N. The reader may wish to try the 100th item of Fibonacci and feel how slow the recursion will be.

2, the interviewer expects the applicable solution:

In fact, the improved method is not complex. The recursive code mentioned above is slow because there are too many repetitions, so we just want to avoid the repetitive computations. For example, we can save the intermediate items that have been obtained, and if we need to find out the next time we have to calculate, we do not have to repeat the calculation if we have already calculated it before.

The simpler approach is to calculate the F (2) in F (0) and F (1), and then the F (2) According to F (1) and F (3) ... You can calculate the nth item by analogy. It is easy to understand that the time complexity of this idea is O (n). The implementation code is as follows:

/**
 * Write a function, enter N, and find the nth term of the Fibonacci (Fibonacci) sequence.
 * *
package swordforoffer;

/**
 * @author Jinshuangqi
 * *
 *
 July 29, 2015
/public class E09fibonacci {public
	long Fibonacci ( int n) {
		long result =0;
		Long preone = 1;
		Long pretwo = 0;
		if (n = = 0) {return
			pretwo;
		}
		if (n = = 1) {return
			preone;
		}
		for (int i = 2;i<= n; i++) {result
			= Preone+pretwo;
			Pretwo = Preone;
			Preone = result;
		}
		return result;
	}
	public static void Main (string[] args) {
		E09fibonacci Fabonacci = new E09fibonacci ();
		System.out.println (Fabonacci.fibonacci);
	}

3, Time complexity O (LOGN) but not enough to use the solution)

Usually the interview here is almost, although we have a faster than this O (Logn) solution, because this algorithm needs to use a very uncommon mathematical formula, so very few interviewers will ask us to master. But just in case, let's introduce the algorithm.

We'll talk first. A mathematical publicity:



Solution Comparison:

The time efficiency of the Fibonacci sequence is very different from the way it is calculated. The first kind of recursive solution, although intuitive but the time efficiency is too low, the actual software development will not use this method, it is impossible to get the favor of the interviewer. The second method uses the recursive algorithm to realize the loop, which greatly improves the time efficiency. The third way to convert the Fibonacci sequence to the exponentiation of the matrix is a very creative algorithm. Although we can yo an O (logn) of the matrix of n-th square, but because of the implied time of Changshu larger, very few software to adopt this algorithm, in addition, the implementation of this algorithm code is also complicated, not very suitable for interview.


Related Topics:

We can cover a larger rectangle with a small rectangular 2*1, either horizontally or vertically. What is the total number of ways to cover a 2*8 rectangle without overlapping with a small rectangle with 8 2*1?



We first write the 2*8 cover method as F (8). Use the first 1*2 small rectangle to cover the leftmost side of the large rectangle with two choices, vertical or horizontal. When placed vertically, the right side is left with a 2*7 area, in which case the coverage method is written as F (7). Then consider the situation sideways. When the 1*2 small rectangle is placed horizontally in the upper-left corner, the upper-left corner must be placed horizontally with a 1*2 small rectangle, and on the right there are 2*6 areas, in which case the coverage method is F (6), so F (8) =f (7) +f (6). At this point, we can see that this is still the Fibonacci sequence.

Extension section:

A frog can jump up to 1 steps at a time, or jump up to level 2 ... It can also jump up n levels. How many jumps are there in total for the frog to jump up the N-level steps?

The FIB (n) is used to denote the number of hops of the frog jumping up n steps, and the jump number of the frog jumping up the N-step step is the definite fib (0) = 1;

When n = 1 o'clock, there is only one method of jumping, that is, 1-step Jump: Fib (1) = 1;

When n = 2 o'clock, there are two kinds of jumps, first and second order jumps: Fib (2) = Fib (1) +fib (0) = 2;

When n = 3 o'clock, there are three kinds of jump method, the first step out of one, after the FIB (3-1) in the Jump method; The first time out of second order, followed by the FIB (3-2) in the Jump method; The first step out of the third, there is fib (3-3) in the Jump method

Fib (3) = Fib (2) +fib (1) +fib (0) = 4

When n= N, there are n kinds of methods of jumping, after the first step out, there are fib (n-1) Jumping method, the first time out of second order, there are fib (n-2) Jumping method, the first time to jump out of the N-order, there are fib (n-n) seed body Oh ah hair.

Fib (n) = Fib (n-1) +fib (n-2) +fib (n-3) +..........+fib (n-n) =fib (0) +fib (1) +fib (2) +.......+fib (n-1)

Also because of Fib (n-1) =fib (0) +fib (1) +fib (2) +.......+fib (n-2)

Two-type subtraction: Fib (n)-fib (n-1) =fib (n-1) ===== "Fib (n) = 2*fib (n-1) n >= 2

The recursive equation is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.