问题描述:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
/**
* 统计出兔子总数。
*
* @param monthCount 第几个月
* @return 兔子总数
*/
public static int getTotalCount(int monthCount)
{
return 0;
}
知识点: 查找,搜索,排序
题目来源: 内部整理
练习阶段: 中级
运行时间限制: 10Sec
内存限制: 128MByte
输入:
输入int型表示month
输出:
输出兔子总数int型
样例输入: 9
样例输出: 34
问题分析:斐波那契数列,从第三个开始,其数字为前面两个的和,1 1 2 3 5 8 13
f(n)=f(n-1)+f(n-2)典型的递归问题
代码:注意,统计的兔子数目,指的是对,不是个
#include <iostream>
using namespace std;
int bunnyCountOneMonth(const int&);//每个月兔子总数
int main()
{
int month,sum=0;
cin>>month;
sum=bunnyCountOneMonth(month);
cout<<sum<<endl;
system("pause");
return 0;
}
int bunnyCountOneMonth(const int& month)//递归
{
if(1==month || 2==month)
{
return 1;
}
else
{
//从第三个月开始,每个月兔子总数都是前两个月的和
return (bunnyCountOneMonth(month-1)+bunnyCountOneMonth(month-2));
}
}