Java经典算法40题 – 题目1

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

思路:很显然是一个递归的问题,计算兔子的数量:1 1 2 3 5 8 13,得出规律:函数出口是月份小于3,其他的就是上个月的兔子数量+上上一个月兔子的数量。

package org.sixlab.algorithm40;

public class Rabbit {
    public static void main(String\[\] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println("第" + i + "个月的兔子数量:" + countRabbit(i));
        }
    }

    public static int countRabbit(int month) {
        if (month <= 0) {
            return 0;
        } else if (month < 3) {
            return 1;
        } else {
            return countRabbit(month - 1) + countRabbit(month - 2);
        }
    }
}
posted @ 2014-03-29 23:23  六楼的雨  阅读(9)  评论(0编辑  收藏  举报