Algorithm-Fibonacci sequence

Fibonacci sequence

Insert picture description here
There are many problems based on the Fibonacci
sequence, for example: the stairs have n steps, and you can go upstairs one step or two steps. How many ways to go upstairs?
Despite the addition of environmental rendering, the essence of the subject is still the Fibonacci sequence, just find out the rules.

Resolving the Fibonacci sequence can use recursion or recursion techniques;
1. Recursion
Recursion is to calculate each item in the sequence according to a certain rule , usually by calculating the previous items to get the sequence Specify the value of the item. The idea is to transform a complex and huge calculation process into multiple repetitions of a simple process. This algorithm takes advantage of the characteristics of fast computers and tireless machines.

int  fib[50];			//采用数组保存中间结果,假设最多不超过50个数
						//若不用数组,用三个变量循环赋值也可代替
int fibonacci(int n)		//参数为所求的第n个数
{
	fib[0] = 1;					
	fib[1] = 1;					//初始化前两位
	for (int i=2; i<=n; i++)
		fib[i] = fib[i-1]+fib[i-2];		//根据规律循环
	return fib[n];
}

2. Recursion
The programming technique that the program directly or indirectly calls itself is called a recursive algorithm.

int fibonacci(int n)
{
	if (n<=1) return 1;		
	return fib(n-1)+fib(n-2);
}

Disadvantages: The efficiency of this algorithm is very low, because the recursion is repeated too many times.

Published 36 original articles · praised 3 · visits 3531

Guess you like

Origin blog.csdn.net/qq_43628835/article/details/105536648