1. 程式人生 > >由易到難學習遞歸的精華

由易到難學習遞歸的精華

rec 阿裏 afn sum 全局變量 能力 while clas -m

以下是收集的一些遞歸實現的小算法,勤加練習,相信每個人都能對簡單的遞歸駕馭自如!

1加到n的一種遞歸的簡潔寫法

int AddFrom1ToN_Recursive(int n)
{
	return n<=0 ?

0 : n+AddFrom1ToN_Recursive(n-1); }


2進制。8進制,16進制的遞歸寫法,原理同樣!

void go2(int nNum)
{
	if (nNum == 0)
		return;
	else
	{
		go2(nNum / 2);
		printf("%d", nNum % 2);
	}
}

void go8(int nNum)
{
	if (nNum == 0)
		return;
	else
	{
		go8(nNum / 8);
		printf("%d", nNum % 8);
	}
}

void go16(int nNum)
{
	if (nNum == 0)
		return;
	else
	{
		go16(nNum / 16);
		printf("%d", nNum % 16);
	}
}


很多時候我們都可以使用一個棧來模擬遞歸中的數據。

想要拿到高薪,就要有實力,怎樣讓別人認為你有實力,就是你寫代碼的能力和寫代碼的速度。反應速度。

多多練習才是王道。

比方說面試官讓你求隨意一個整數有多少位的for,while,go..while,goto,遞歸實如今10分鐘以內實現。就能考察你的代碼能力。

求隨意一個整數有多少位的for,while,go..while,goto,遞歸實現


wei++;
for (; num; num /= 10)
{
	wei++;
}

while (num)
{
	wei++;
	num /= 10;
}

do 
{
	wei++;
	num /= 10;
}while (num);

AAA:
if (num)
{
	num /= 10;
	wei++;
	goto AAA;
}


5050-100-99-98-....-1 for,while,do...while,goto,遞歸實現

int Reduce(int sum, int n)
{
	if (n == 0)
		return sum;
	else
	{
		return Reduce(sum-=n, n - 1);
	}
}


以下是求二叉樹葉子結點的個數的遞歸算法。註意使用全局變量和使用函數傳參的方式保存葉子結點個數的異同。

要特別掌握另外一種遞歸的使用方法。


int sum = 0;
int DLR_CountLeafNum(BiTNode *root)//採用中序遍歷的遞歸算法
{ 
	if ( root)  //非空二叉樹條件,還可寫成if(root !=NULL )
	{   
		if(!root->lchild && !root->rchild)  //是葉子結點則統計並打印
		{   
			sum++;     
			printf("%c\n",root->data);  
		}
		DLR_CountLeafNum(root->lchild); //遞歸遍歷左子樹,直到葉子處;
		DLR_CountLeafNum(root->rchild);//遞歸遍歷右子樹。直到葉子處。
}

	return(0);  
}

 
int DLR_CountLeafNum2(BiTNode *root, int *psum)//採用中序遍歷的遞歸算法
{ 
	if ( root)  //非空二叉樹條件。還可寫成if(root !=NULL )
	{   
		if(!root->lchild && !root->rchild)  //是葉子結點則統計並打印
		{   
			(*psum) ++;     
			printf("%c\n",root->data);  
		}
		DLR_CountLeafNum2(root->lchild, psum); //遞歸遍歷左子樹,直到葉子處;
		DLR_CountLeafNum2(root->rchild, psum);//遞歸遍歷右子樹,直到葉子處;
}

	return(0);  
}

阿裏巴巴面試題 用遞歸推斷一個數組是否是遞增數組

bool test1(int arr[], int n)
{
	if (n == 0)
		return true;
	return test1(arr, n - 1) && arr[n]>arr[n - 1];
}

bool test2(int arr[], int n)
{
	if (n == 1)
		return true;
	else if (n == 2)
		return arr[n-1] > arr[n-2];
	else
		return test2(arr, n - 1) && arr[n-1] > arr[n - 2];
}

//由斐波那契數列引出的面試題,跳臺階
//一次能夠調1級,2級,3級
int step(int nStep)
{
	if (1 == nStep)
		return 1;
	else if (2 == nStep)
		return 2;
	else if (3 == nStep)
		return 4;
	else
		return step(nStep - 1) + step(nStep - 2) + step(nStep - 3);
}

//一次能夠調1級,2級
int taijie(int n)
{
	if (1 == n)
		return 1;
	else if (2 == n)
		return 2;
	else
		return taijie(n - 1) + taijie(n - 2);
}


由易到難學習遞歸的精華