java编程:斐波那契数列经典案例:兔子问题

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

package com.java.recursion;

/**
* @描述 三种方法实现斐波那契数列
* @项目名称 Java_DataStruct
* @包名 com.java.recursion
* @类名 Fibonacci
* @author chenlin
* @date 2011年6月17日 下午8:44:14
*/
public class Fibonacci {
/**
* 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,
* 问每个月的兔子总数为多少?
* month 1 2 3 4 5 6
* borth 0 0 1 1 2 3
* total 1 1 2 3 5 8
*/

    /**
     * 叠加法
     * 
     * @param month
     * @return
     */
    public static int getTotalByAdd(int month) {
        int last = 1;//上个月的兔子的对数 
        int current = 1;//当月的兔子的对数
        int total = 1;
        for (int i = 3; i <= month; i++) {
            //总数= 上次+当前
            total = last + current;
            last= current ;
            current = total;
        }
        return total;
    }

    /**
     * 使用数组
     * 
     * @param month
     * @return
     */
    public static int getTotalByArray(int month) {
        int arr[] = new int[month];
        arr[1] = arr[2] = 1;
        for (int i = 2; i < month; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        return arr[month - 1] + arr[month - 2];
    }

    public static int getTotalByRecusion(int month) {
        if (month == 1 || month == 2) {
            return 1;
        } else {
            return getTotalByRecusion(month - 1) + getTotalByRecusion(month - 2);
        }
    }

    public static void main(String[] args) {
        System.out.println(getTotalByAdd(3));
        System.out.println(getTotalByAdd(4));
        System.out.println(getTotalByAdd(5));
        System.out.println(getTotalByAdd(6));
    }
}

—————————————————–
(java 架构师全套教程,共760G, 让你从零到架构师,每月轻松拿3万)
请先拍 购买地址, 下载请用百度盘
目录如下:
01.高级架构师四十二个阶段高
02.Java高级系统培训架构课程148课时
03.Java高级互联网架构师课程
04.Java互联网架构Netty、Nio、Mina等-视频教程
05.Java高级架构设计2016整理-视频教程
06.架构师基础、高级片
07.Java架构师必修linux运维系列课程
08.Java高级系统培训架构课程116课时
(送:hadoop系列教程,java设计模式与数据结构, Spring Cloud微服务, SpringBoot入门)

01高级架构师四十二个阶段高内容:
这里写图片描述
这里写图片描述
—————————————————–

你可能感兴趣的:(Java-数据结构)