69,371
社区成员
发帖
与我相关
我的任务
分享
我看楼主第一次接触,我就显摆一下,同时楼主要是有心人会进一步去探究递归算法。有什么不好的,老哥你真酸 就是以空间换时间
这个是最基础的解法,没人说是下效率高啊
就是以空间换时间
vector<int> record;
int func_1(int n) {
if (n == 1 || n == 2) {
record[n] = 1;
return record[n];
}
if (record[n])
return record[n];
else {
record[n] = func_1(n-1) + func_1(n-2);
return record[n];
}
}
int func(int n) {
if (n == 1 || n == 2) {
return 1;
}
return func(n - 1) + func(n - 2);
}
int main() {
int N=0;
cout << "求第N位斐波那契数:" << endl;
cin >> N;
record.assign(N+1,0);
DWORD start;
start = GetTickCount();
cout<<func(N)<<endl;
cout << "直接递归的用时:" <<(GetTickCount() - start) << endl;
start = GetTickCount();
cout << func_1(N) << endl;
cout << "优化重复运算的用时:"<<(GetTickCount() - start) << endl;
system("pause");
return 0;
}
对比一下运算用时:
当运算靠前的斐波那契额数时
当运算大斐波那契数时: