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

来源:互联网 发布:千万别去淘宝搜索 编辑:程序博客网 时间:2024/05/15 04:07

题目:古典问题:有一对兔子,从出生后第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));    }}
0 0