描述
有一种兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子。
例子:假设一只兔子第3个月出生,那么它第5个月开始会每个月生一只兔子。
一月的时候有一只兔子,假如兔子都不死,问第n个月的兔子总数为多少?
数据范围:输入满足 1 \le n \le 31 \1≤n≤31
输入描述:
输入一个int型整数表示第n个月
输出描述:
输出对应的兔子总数
示例1
输入:
3
复制输出:
题解:通过画出前5个月对应的每个月兔子数,很容易发现符合斐波拉契数列,使用递归法可以得到最终结果。
#include <iostream>
#include <string.h>
#include <algorithm>
#include <string.h>
#include <sstream>
int RabbitCount(int num)
{
if(num == 1 || num == 2)
{
return 1;
}
return RabbitCount(num - 1) + RabbitCount(num - 2);
}
int main()
{
int n;
std::cin >> n;
int count = RabbitCount(n);
std::cout << count << std::endl;
return 0;
}