递归算法

什么是递归

狐狸老师收作业

1号学生

2号学生

1号学生

3号学生

4号学生

递归算法

递归算法是一种“自己调自己”,“有去有回”的算法,

在调用一个函数的过程中又出现直接或间接的调用该函数本身,但是调用的过程不是一个无休止的,而是有限次数的,总要有结束调用

递归的实现

利用递归算法,试编一程序,算一算狐狸老师收到多少本作业

#include <iostream>

using namespace std;

int work(int n){
	if(n == 7){		//设置递归结束条件,当n为0的时候结束递归
		return 1;
	}else{
		return work(n+1)+1;	//求出返回结果加1的值
	}
}

int main(){
	int result = work(1);

	cout << result << endl;

	return 0;
}

实现过程

综合练习

例题一:

请使用递归的方式来计算n的阶乘

Answer

#include <iostream>

using namespace std;

int factorial(int n){
	if (n == 1){	//设置递归条件
		return 1;
	}else
		return factorial(n-1)*n;	//调用自己
}

int main(){
	int result = factorial(4);

	cout << result << endl;

	return 0;
}

例题二:

输出斐波那契数列的第n项

斐波那契数列:后一个数字等于前两个数之和

例子:1,1,2,3,5,8,13,21

Answer

#include <iostream>

using namespace std;

int fibonacci(int n){
	if (n < 3){		//结束条件
		return 1;
	}else{
		return fibonacci(n-1)+fibonacci(n-2);	//调用自己
	}
}

int main(){
	int n;

	cin >> n;

	int result = fibonacci(n);

	cout << result << endl;
}

例题三:

利用递归算法,试编一程序,输出1~100的自然数

#include <iostream>

using namespace std;

void  print_number(int n){
	if (n >= 1){
		cout <<  n << " ";
		print_number(n-1);
	}
}

int main(){
	print_number(100);
}

Answer

例题四:

利用递归算法,试编一程序,计算数组当中最大值

#include <iostream>

using namespace std;


int _max(int *p,int len){
	if (len == 1){	//设置终止条件
		return p[0];
	}

	int max_item = _max(++p,len-1);	//求出最大值

	if (max_item > p[0]){	//求出最大值的条件
		return max_item;
	}else{
		return p[0];
	}
}

int main(){
	int a[]={45,24,100,24,77,22,67,89};
	int max = _max(&a[0],sizeof(a)/sizeof(a[0]));
	cout << max << endl;

	return 0;
}

Answer

Level2_2_1递归算法

By yang he

Level2_2_1递归算法

  • 240