递归运算

递归算法是将问题返回到自身的上一种状态来解决问题的过程。

其中1、每个递归定义必须具有一个(或多个)边界条件。

2、一般条件必须最后返回到边界条件

3、由边界条件停止递归。

接下来是一个应用递归来比较最大值的问题,当然也可以应用一般的迭代法进行求解:

//递归法求最大值
#include<iostream>
using namespace std;
int largest(const int list[], int lowerIndex, int upperIndex);
int main()
{
	int intArray[10] = { 23, 43, 35, 38, 67, 12, 76, 10, 34, 8 };
	cout << "The largest element in intArray:" << largest(intArray, 0, 9);
	cout << endl;
	return 0;
}
int largest(const int list[], int lowerIndex, int upperIndex)
{
	int max;
	if (lowerIndex == upperIndex)
		return list[lowerIndex];
	else
	{
		max = largest(list, lowerIndex + 1, upperIndex);
		if (list[lowerIndex] >= max)
			return list[lowerIndex];
		else
			return max;
	}
}

下面是迭代法求最大值:

//迭代法求最大值
#include<iostream>
using namespace std;
int main()
{
	int intArray[10] = { 23, 43, 35, 38, 67, 12, 76, 10, 34, 8 };
	int  max=0;
	int i;
	for (i = 0; i < 10; i++)
	{
		if (intArray[i]>max)
			max = intArray[i];
	}
	cout << "The largest element in intArray:" << max << endl;
	return 0;
} 

下面是计算斐波那契数列:

//递归法求斐波那契数列
#include<iostream>
using namespace std;
int rFibNum(int a, int b, int n);
int main()
{
	int firstFibNum;
	int secondFibNum;
	int nth;
	cout << "Enter the first Fibonacci number:";
	cin >> firstFibNum;
	cout << endl;
	cout << "Enter the second Fibonacci number:";
	cin >> secondFibNum;
	cout << endl;
	cout << "Enter the position of the desired Fibonacci number:";
	cin >> nth;
	cout << endl;
	cout << "the Fibonacci number at position " << nth << "is " << rFibNum(firstFibNum, secondFibNum, nth) << endl;
	return 0;
}
int rFibNum(int a, int b, int n)
{
	if (n == 1)
		return a;
	else if (n == 2)
		return b;
	else
		return rFibNum(a, b, n - 1) + rFibNum(a, b, n - 2);
}

迭代法求斐波那契数列

//迭代法求斐波那契数列
#include<iostream>
using namespace std;
int main()
{
	int nth,i;
	int FibNum[133];
	cout << "Enter the first Fibonacci number:";
	cin >> FibNum[1];
	cout << endl;
	cout << "Enter the second Fibonacci number:";
	cin >> FibNum[2];;
	cout << endl;
	cout << "Enter the position of the desired Fibonacci number:";
	cin >> nth;
	cout << endl;
	for (i = 3; i <= nth; i++)
	{
		FibNum[i] = FibNum[i - 1] + FibNum[i - 2];

	}
	cout << "the Fibonacci number at position " << nth << "is " << FibNum[nth] << endl;
	return 0;
}

综上,迭代控制结构使用循环结构(while、for、do while)来重复一系列语句。

递归通过使函数调用自身来重复一系列语句。与同等的迭代运算相比,递归函数执行速度较慢。但是对于一些特定问题来说(例如汉诺塔问题)迭代解决起来就非常困难。所以,特定问题特定分析。


猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/80308167