目录
牛客HJ37 统计每个月兔子的总数
解析代码
第n个月的兔子数量由两部分组成,一部分是上个月的兔子f(n-1),另一部是满足3个月大的兔子,会生一只兔子f(n-2)。所以第n个月兔子总数: f(n) = f(n - 1) + f(n - 2)。本题是在变相考察斐波那契数列。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 0;
cin >> n;
vector<int> arr(n + 1, 0);
arr[1] = 1, arr[2] = 1, arr[3] = 2; // 3 5
int cnt = 1; // 下一月会生的
for (int i = 4; i <= n; ++i)
{
arr[i] = arr[i - 1] + cnt;
cnt = arr[i - 1];
}
// for(auto& e : arr)
// {
// cout << e << ' ';
// }
// cout << endl;
cout << arr[n];
return 0;
}