用静态数组在函数递归过程中保存中间数据(以递归输出斐波那契数列为例——详细注释)

核能气质少年 提交于 2019-12-01 20:52:45

通过建立一个静态数组来保存递归函数调用过程中产生的中间数据,可以规避掉很多不必要的重复计算, 能在很大程度上提高程序的运行效率,尤其是在动态规划等需要递归调用的算法中应用广泛。
下面以递归输出斐波那契数列为例, 通过建立一个静态数组,来使得程序运行避免超时。

#include<stdio.h>
long int count[1000];//establish an array to store the temporary data during the recursion calculation.
long int fibo(int i)
{
	if (i == 2 || i == 1)
		return 1;
	else if(count[i - 1] != 0 && count[i - 2] != 0)
		{
		 	 return count[i - 1] + count[i - 2];
		}// take a value from the array before assigning a value to the array to reduce the unnecessary judgement.
	else 
		{
			count[i - 1] = fibo(i - 1);
			count[i - 2] = fibo(i - 2);
			return count[i - 1] + count[i - 2];
		}
}
int main()
{
	long int i;
	scanf("%ld", &i);
	printf("%ld", fibo(i));
	return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!