有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
/**
* 统计出兔子总数。
*
* @param monthCount 第几个月
* @return 兔子总数
*/
public static int getTotalCount(int monthCount)
{
return 0;
}
因为一直兔子在生下来第三个月才会有小兔子,那么可以看为f(n)=f(n-1)+f(n-2)。此题有两个思路一个是正着算,一个是反着算。
1)正着算 从第三个月开始兔子是增加的,就等于前两个月之和
2)反着算,运用递归
#include <iostream>
using namespace std;
int fun(int n)
{
if (n < 3) //运用递归计算
return 1;
return fun(n - 1) + fun(n - 2);
}
int main() {
int month;
while (cin >> month) {
int first = 1;
int second = 1;
int result = 2;
int temp;
for (int i = 0; i < month - 3; i++)
{
temp = result;
result = result + second;
first = second;
second = temp;
}
cout << result << endl;
}
return 0;
}