记录一下使用暴力递归、记忆化搜索和动态规划解决Fibonacci数列问题的优化。
这里使用了对数器来判断解法的正确性。
用了时间函数来观察运行时间的差异性。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<windows.h>
//Fibonacci数列的优化
//暴力递归
int f(int n){if(n == 1 || n == 2){return 1;}else{return f1(n - 1) + f1(n - 2);}
}
//记忆化搜索
int f1(int n, int dp[]){if(n == 1){return dp[1];}else if(n==2){return dp[2];}else if(dp[n] != 0){return dp[n];}else{dp[n-1] = f(n - 1, dp);dp[n-2] = f(n - 2, dp);return dp[n-1] + dp[n-2];}
}
//动态规划
int f2(int n, int dp[]){int i;for(i = 3; i <= n; i++){dp[i] = dp[i - 1] + dp[i - 2];}return dp[n];
}//随机数生成器
int getRandom(int max){return 1 + rand() % max;
}
//对数器
int Compare(int n, int dp[]){int times = 1000;int max = 100;int i;for(i = 0; i < times; i++){int x = getRandom(max);if(f1(n) != f2(n, dp)){printf("错了");}}printf("结束");
}
int main(int argc, char *argv[], char *envp[]){int n = 500;//计时器开始 LARGE_INTEGER frequency;LARGE_INTEGER start;LARGE_INTEGER end;double executionTime;QueryPerformanceFrequency(&frequency);QueryPerformanceCounter(&start);//int dp[n + 1];int i;for(i = 0; i <= n; i++){dp[i] = 0;}dp[1] = 1;dp[2] = 1;//对数器
// Compare(n, dp);long long a = f2(n, dp);//计时器结束 QueryPerformanceCounter(&end);executionTime = (double)(end.QuadPart - start.QuadPart) / frequency.QuadPart;printf("有记忆搜索用时:%f\n,结果:%d", executionTime, a);//return 0;
}