遞歸與遞推:一隻小蜜蜂

有一隻經過訓練的蜜蜂只能爬向右側相鄰的蜂房,不能反向爬行。請編程計算蜜蜂從蜂房a爬到蜂房b的可能路線數。 
其中,蜂房的結構如下所示。 

Input

輸入數據的第一行是一個整數N,表示測試實例的個數,然後是N 行數據,每行包含兩個整數a和b(0<a<b<50)。 

Output

對於每個測試實例,請輸出蜜蜂從蜂房a爬到蜂房b的可能路線數,每個實例的輸出佔一行。 

Sample Input

2
1 2
3 6

Sample Output

1
3

【分析】

主要抓住對於每一個終點b,都等於其左邊的兩個蜂房的路線數之和。即:f(b)=f(b-1)+f(b-2)。

【代碼】

我本人採用的是遞歸的思想,從終點b往回遞歸到a:

#include<iostream>
using namespace std;
int f(int a, int b)
{
	int res=0;
	//終止條件 
	if((b-a)==1)
	{
		res = 1;
	}
	else if((b-a)==2)
	{
		res = 2;
	}
	else
	{
		res=f(a,b-1)+f(a,b-2);//遞歸的規律
	}
	
	return res;
}
int main()
{
	int N;
	cin>>N;
	int* arr = new int[N*2];
	for(int i=0;i<N;i++)
	{
		int a,b;
		cin>>a>>b;
		arr[i*2]=a;
		arr[i*2+1]=b;

        int res=f(a,b);
		cout<<res<<endl;
	}

	return 0;
}

題解採用的是遞推的思想,即從蜂房a出發,由前一個結果一遍遍推出後一個結果:

#pragma warning(disable:4996) //將4996報警置爲失效
#include <iostream> 
#include<cstdio> 
#include<cmath> 
#include<cstring> 
#include<algorithm> 
#include<map> 
long long ans[55]; 
int main() 
{
  int t;
  scanf("%d", &t);
  while (t--)  //這個製造循環輸入的方法值得借鑑
  {   
    int s,t;
    memset(ans, 0, sizeof(ans));//將數組ans全部賦爲0
                                //作用是將某一塊內存中的內容全部設置爲指定的值, 這個函數通常爲新申請的內存做初始化工作。它是對較大的結構體或數組進行清零操作的一種最快方法。
                                //# include <string.h> void *memset(void *s, int ch, size_t n);
	scanf("%d%d", &s, &t);
    ans[s] = 1;   //把開始的蜂房置爲1,意思是其到右邊的相鄰蜂房路線數爲1
	for (int i = s + 1; i <= t; i++)
	{    
	  ans[i] = ans[i - 1] + ans[i - 2];  //s=1時,ans[2]=ans[1]+ans[0],此時ans[0]=0,很巧妙
	}   
	printf("%lld\n", ans[t]);  
  }  
  system("pause");  
  return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章