奶牛生子问题----------腾讯面试
题目:一只刚出生的奶牛,4年生一只奶牛。以后每一年生一只,现在给你一只刚出生的奶牛,求20年后有多少奶牛,考核分析能力
本题难点在于:不光这只奶牛会生奶牛,它的孩子的孩子也会生奶牛。
#include<iostream>
using namespace std;
int Cal(int year)//法一
{
if (year < 4)
return 1;
return Cal(year - 4) + Cal(year - 1);
}
int CalCowsNum(int year)//法二
{
int cnt = 0;
long cowsNum = 1;//奶牛总数
for (cnt = 1; cnt <= year; ++cnt)
{
if (cnt >= 4)
{
if ((year - cnt) > 3)
{
cowsNum += CalCowsNum(year - cnt);
}
else
{
cowsNum++;
}
}
}
return cowsNum;
}
int main()
{
int year = 20;
cout << CalCowsNum(year) << endl;
system("pause");
return 0;
}