递归:通俗讲即自己调用自己

题目:母牛的故事:一头母牛每年初生一头小母牛,小母牛到第四年时也开始生小牛,第n年,一共会有多少头牛?(0<n<55)

这是一个典型的递归问题,可以参考斐波拉契数列,来理解递归思想。

第n年1234567
f [n] 头牛12346913

找规律,明显 f [n] = f [n-1] + f [ n-3 ] ;

附上代码

数组方式解决,比较清晰,也可以自定义函数。

数组:

#include<iostream>

using namespace std;

int main()
{
    int n,i;
    int f [55] = {0,1,2,3}; // f [0] =0; f [1] =1; f [2] =2; f [3] =3;
    for(i=4; i<=55; i++)
    {
        f[i]=f[i-1]+f[i-3];
    }
    while(cin>>n&&n!=0)
    {
        cout<<f[n]<<endl;
    }
    return 0;
}

自定义函数:

#include<iostream>

using namespace std;

int Feibo(int n)
{
	if(n==1) return 1;
	if(n==2) return 2;
	if(n==3) return 3;
	else return Feibo(n-1)+Feibo(n-3);   ///!!!
}

int main()
{
	int res=0;     //牛的总数
	while(cin>>n&&n!=0)
	{
		res=Feibo(n);  //调用函数 
		cout<<res<<endl;
	}
	return 0; 
 } 


补充:斐波拉契数列   1   1   2   3   5   8   13   21   34.......同样思想

#include<iostream>

using namespace std;

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

int main()
{
	int res=0;     
	while(cin>>n&&n!=0)
	{
		res=Feibo(n);  //调用函数 
		cout<<res<<endl;
	}
	return 0; 
 } 



 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐