使用传统递归算法和记忆化搜索算法的耗时比较
#include <ctime>
#include <cstdio>
#include "algorithm"
using namespace std;
int dp[1000];
clock_t start, finish;
double duration;
int F1(int n) {
if (n == 1 || n == 0)
return 1;
else
return F1(n - 1) + F1(n - 2);
}
int F2(int n) {
if (n == 1 || n == 0)
return 1;
else if (dp[n] != -1)
return dp[n];
else {
dp[n] = F2(n - 1) + F2(n - 2);
return dp[n];
}
}
int main() {
fill(dp, dp + 1000, -1);
start = clock();
int d1 = F1(40);
finish = clock();
duration = (double) (finish - start) / CLOCKS_PER_SEC;
printf("%f seconds\n", duration);
//记忆化搜索
start = clock();
int d2 = F2(40);
finish = clock();
duration = (double) (finish - start) / CLOCKS_PER_SEC;
printf("%f seconds\n", duration);
printf("d1:%d d2:%d", d1, d2);
}
耗时: