通过建立一个静态数组来保存递归函数调用过程中产生的中间数据,可以规避掉很多不必要的重复计算, 能在很大程度上提高程序的运行效率,尤其是在动态规划等需要递归调用的算法中应用广泛。
下面以递归输出斐波那契数列为例, 通过建立一个静态数组,来使得程序运行避免超时。
#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;
}
来源:CSDN
作者:写bug战神
链接:https://blog.csdn.net/qq_40064490/article/details/84207652