Algorithms - Fibonacci number

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45505313/article/details/102766359

1. Fibonacci number

Many programming problems and Fibonacci number related to, or can be seen as another expression deed Fibonacci number sequence, such as a classic frog jump step problems

  • A frog can jump on a Class 1 level, you can also hop on level 2, find the frog jumped into a total of n grade level how many jumps (the order of different calculation different results)

2. Solution

Fibonacci is essentially a problem,For the n-th step, we can jump from the step n-1 or n-2 to, the
F (n) = F (n -1) + F (n-2)

	/**
	 *  斐波那契数列问题
	 * 1.数组实现  1 1 2 3 5 8 13....
	 *   a[0]=1,a[1]=1;
	 *   a[x>=2]=a[x-1]+a[x-2];
	 * 
	 * 2.变量变化实现   a   b
	 *                 1   1
	 *                 1   2
	 *                 2   3
	 *                 3   5
	 *                 5   8
	 *   a=1,b=1;
	 *   tem=a;
	 *   a=b;
	 *   b=b+tem;
	 * 3.递归实现
	 */
   public static int fib(int n) {
		if (n == 0)
			return 0;
		if (n == 1 || n == 2) {
			return n;
		} else {
			return fib(n - 1) + fib(n - 2);
		}
	}

Guess you like

Origin blog.csdn.net/weixin_45505313/article/details/102766359