您的位置:首页 > 其它

我的第一个动态规划程序(试图用递归求斐波拉契数)

2012-04-07 14:31 288 查看
1、这是一般的递归(指数爆炸型,时间复杂度O(1.618^n)):

#include <iostream>
#include <cstdio>
using namespace std;

__int64 Fib(int n)
{
if(n == 1 || n == 2)
return 1;
return Fib(n - 1) + Fib(n - 2);
}

int main(void)
{
int n;
while(cin >> n)
printf("%I64d\n", Fib(n));
return 0;
}


2、今天看了动态规划的入门,觉得建备忘表的方法挺不错的,也是符合人的思维的(这很重要),于是就类比,写了带备忘表的递归求斐波拉契数,这应该是以空间换时间吧,备忘表是全局的,一但建起,之后的就好办了。

#include <iostream>
#include <cstdio>
using namespace std;

__int64 aFib[90] = {0};				//	aFib[] correspond to Fib(), and global!

__int64 Fib(int n)
{
if(n == 1 || n == 2)
return 1;
if(aFib[n - 1] == 0)			//	Fib(n-1) have been not calculated
aFib[n - 1] = Fib(n - 1);
if(aFib[n - 2] == 0)			//	Fib(n-2) have been not calculated
aFib[n - 2] = Fib(n - 2);
return aFib[n - 1] + aFib[n - 2];
}

int main(void)
{
int n;
while(cin >> n)
printf("%I64d\n", Fib(n));
return 0;
}

这是我学习动态规划的第一个应用,纪念一下!虽然还没充分体现动态规划(求最优解)的魅力。继续学习中。。。

2012/4/8 更新

原来这种方法叫 搜索+动态规划,顺便简化了第二个程序:

#include <iostream>
#include <cstdio>
using namespace std;

__int64 aFib[90] = {0, 1, 1};	//	aFib[] correspond to Fib(), and global!

unsigned __int64 Fib(const unsigned int n)
{
if(aFib
== 0)			//	Fib(n) have been not calculated
aFib
= Fib(n - 1) + Fib(n - 2);
return aFib
;
}

int main(void)
{
int n;
while(cin >> n)
printf("%I64d\n", Fib(n));
return 0;
}


2012/5/11 更新

通项公式法,时空复杂度都是O(1)

#include <iostream>
#include <cstdio>
using namespace std;

int main(void)
{
int n;
while(cin >> n)
printf("%.0f\n", 0.4472135955 * pow(1.618033988745, n) );

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: