/*
动态规划
*/
#include <iostream>
#include <ctime> // time
using namespace std;
// old
long long fib_old(long long n){
if (n == 0 || n == 1){
return n;
} else {
return fib_old(n - 1) + fib_old(n - 2);
}
}
// new
long long fib_new(int n){
if (n == 0 || n == 1) {
return n;
} else {
long long array[1000];
array[0] = 0;
array[1] = 1;
int i = 2;
while (i <= n) {
array[i] = array[i - 1] + array[i - 2];
i++;
}
return array[n];
}
}
int main(){
long long ans;
time_t time_1, time_2;
// old
time_1 = time(nullptr);
ans = fib_old(45);
time_2 = time(nullptr);
cout << time_2 - time_1 << endl;
cout << "old: \t" << ans << endl;
// new
time_1 = time(nullptr);
ans = fib_new(45);
time_2 = time(nullptr);
cout << time_2 - time_1 << endl;
cout << "new: \t" << ans << endl;
return 0;
}
/*
Launching: '/Users/daidai/Desktop/cpp_code/a.out'
Working directory: '/Users/daidai/Desktop/cpp_code'
1 arguments:
argv[0] = '/Users/daidai/Desktop/cpp_code/a.out'
9
old: 1134903170
0
new: 1134903170
Process exited with status 0
[进程已完成]
*/
动态规划 cpp
最新推荐文章于 2023-05-20 18:03:08 发布