我们熟悉的费氏数列也是典型的动态规划的问题。
方法一:
首先用我们常用的递归方法求解:
#include<iostream>
#include<algorithm>
#include<ctime>
using namespace std;
int F1(int n)
{
if (n == 1)
return 1;
if (n == 2)
return 1;
return F1(n - 1) + F1(n - 2);
}
int main()
{
int n;
cout << "请输入n的值:";
while (cin >> n)
{
time_t time1, time2;
time1 = clock();
long long result = F1(n);
time2 = clock();
cout << "F(n) = " << result << "\t耗时:" << (double)(time2 - time1) / CLOCKS_PER_SEC << endl;
}
cout << __DATE__ << " " << __TIME__ << endl;
system("pause");
return 0;
}
运行结果: