若一头小母牛,从出生起第四个年头开始每年生一头母牛,按此规律,第n年时有多少头母牛?
先写出函数表达式:f(n)=f(n-1)+f(n-3)
为什么f(n)=f(n-1)+f(n-3)呢,请看:
f(n)-f(n-1)=f(n-3)
因为第n年要比n-1年多的牛,都是大于三岁的牛生的小牛,而f(n-3)正是那些在n年大于三岁的牛,然后它们在第n年生下相同数量的小牛。
递归实现(假设第一年有1头小牛):
return cal(i - 1) + cal(i - 3);
}
int main(int argc, char *argv[])
{
int year;
cout << "please input year N: " << endl;
cin >> year;
cout << "year " << year <<"th's count is: " << cal(year) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
非递归实现:
int a[4] = {1, 1, 1, 0};
int i;
for(i=3; i<year; i++)
a[i % 4] = a[(i - 1) % 4] + a[(i - 3) % 4];
cout << "year " << year <<"th's count is: " << a[(i - 1) % 4] << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
上面使用了滚动数组, 这个概念不久前听说的, 拿来试下...