本文共 838 字,大约阅读时间需要 2 分钟。
2021-05-10
学习视频:
斐波那契数列是递归的典型应用;
①,前两项数除外,都是1;
②,从第三项起,每一个数都是它前两个数的和;
比如:1 1 2 3 5 8 13 21 ...
代码:
package per.zhangyh.algorithm.data_structure.code;/** *@author:zhangyonghui; *@date: 2021/5/10; 7:50 *@Describe: 递归与斐波那契数列 */public class FeiBoNaQie { /* 什么是斐波那契数列: ①,前两项数除外,都是1; ②,从第三项起,每一个数都是它前两个数的和; 比如:1 1 2 3 5 8 13 21 ... */ public static void main(String[] args) { System.out.println("斐波那契数列 = " + getFeiBoNaQieNum(6)); } /** * todo 返回指定位置的斐波那契数 * @param index:指定的位置 */ public static int getFeiBoNaQieNum(int index) { if (index == 1 || index == 2) { //如果是第一个数和第二个数 return 1; }else{ //从第三项起,每一个数都是它前两个数的和 int num = (getFeiBoNaQieNum(index - 1) + getFeiBoNaQieNum(index - 2)); //这里就用到了递归 return num; } }}
转载地址:http://lytzi.baihongyu.com/