【牛客网】统计每个月兔子的总数

题目描述

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

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

示例

输入 9
输出 34

解题思路

第n个月的兔子数量由两部分组成,一部分是上个月的兔子f(n-1),另一部是满足3个月大的兔子,会生一只兔子f(n2)。所以第n个月兔子总数: f(n) = f(n -1) +f(n -2)。本题是在变相考察斐波那契数列。

完整代码

#include 
using namespace std;

int Count(int n)
{
	if (n == 1 || n == 2)
		return 1;
	else
		return Count(n - 1) + Count(n - 2);
}

int main()
{
	int n;
	while (cin >> n)
	{
		cout << Count(n) << endl;
	}
	return 0;
}

原题链接

https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395?tpId=37&&tqId=21260&rp=1&ru

你可能感兴趣的:(练习题,算法思想)