Java编程题:斐波那契数列应用——统计每个月兔子的总数

统计每个月兔子的总数

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

/**
 * 统计出兔子总数。
 * 
 * @param monthCount 第几个月
 * @return 兔子总数
 */
public static int getTotalCount(int monthCount)
{
    return 0;
}

输入描述:
输入int型表示month
输出描述:
输出兔子总数int型

示例1
输入
9
输出
34

简单理解:
以1-6月的兔子数量为例,黑色代表成熟的兔子,白色代表未成熟的兔子。
1
图片转自:https://blog.csdn.net/DERRANTCM/article/details/51343986

在当前月份month<=2时兔子的数量都是1,在当前月份month>=3时,month-2时的兔子在当前month月份都会再生兔子,即在month-2时的兔子,在month-1时成熟,在month月份生兔子。即在当前月份的兔子数量为month-1时兔子的数量加上在month-2月份的兔子在当前月份新增兔子数量(新增的兔子即为month-2时兔子的数量)。

此时就有fuc(month)=func(month-1)+func(month-2);此处应用递归的思想解题——典型的斐波那契数列。不断递归,一月份和二月份作为函数出口。

import java.util.Scanner;
public class Main{
	public static int getTotalCount(int month){
		if(month==1||month==2){
			return 1;
		}
		return getTotalCount(month-1)+getTotalCount(month-2);
	}
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			int month=sc.nextInt();
			System.out.println(getTotalCount(month));
		}
	}
}
动态规划求解:

状态:每个月的兔子数量F(i)
状态递推: F(i) = F(i-1)+ F(i-2)
初始值:F(1)=F(2) = 1
返回值:F(n)

import java.util.Scanner;
public class Main{
    public static int getTotalCount(int month){
        if(month==1||month==2){
            return 1;
        }
        int mon1 =1;
        int mon2 =1;
        int ret =0;
        for(int i=3;i<=month;i++){
            ret = mon1+mon2;
            mon1=mon2;
            mon2 = ret;
        }
        return ret;
}
    
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    while(sc.hasNext()){
        int month=sc.nextInt();
        System.out.println(getTotalCount(month));
    }
}
}

来源:牛客网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值