f(n) = f(n-1)+f(n-2)
1,2,3,5,8.....
自顶向下使用的递归层次比较多,在n取值较大的情况下,效率很低(时间维度)
所以可以使用数组来替换多重递归调用,即以空间来置换时间(intersting)
#include <stdio.h>
#include <error.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#define ERROR -22
#define DEBUG 0
static long int feibonaqie_toptolow(int n)
{
int max = pow(2,(sizeof(int)*8)-1)-1;
if(n<=0||n>max){
return ERROR;
}
if(n==1){
return 1;
}
if(n==2){
return 2;
}
long int ret = 0;
ret = feibonaqie_toptolow(n-1)+feibonaqie_toptolow(n-2);
return ret;
}
static long int feibonaqie_lowtotop(int n)
{
int max = pow(2,(sizeof(int)*8)-1)-1;
if(n<=0||n>max){
return ERROR;
}
int i =0;
long int arr[n];
arr[1] = 1;
arr[2] = 2;
for(i=3; i<=n; i++){
arr[i] = arr[i-1]+arr[i-2];
}
//printf("arr[%d] is %ld\n", i-1, arr[i-1]);
return arr[i-1];
}
int main()
{
struct timeval start, end;
float timeuse = 0.0;
gettimeofday(&start, NULL);
printf("%ld\n", feibonaqie_toptolow(40));
gettimeofday(&end, NULL);
timeuse = (1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec)/1000.0;
printf("time_use is %.2fms\n", timeuse);
gettimeofday(&start, NULL);
printf("%ld\n", feibonaqie_lowtotop(40));
gettimeofday(&end, NULL);
timeuse = (1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec)/1000.0;
printf("time_use is %.2fms\n", timeuse);
}
看一个执行效果:
$ ./a.exe
165580141
time_use is 677.24ms
165580141
time_use is 0.00ms