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

来源:互联网 发布:windows api 删除文件 编辑:程序博客网 时间:2024/05/20 03:07

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 calculatedaFib[n - 1] = Fib(n - 1);if(aFib[n - 2] == 0)//Fib(n-2) have been not calculatedaFib[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[n] == 0)//Fib(n) have been not calculatedaFib[n] = Fib(n - 1) + Fib(n - 2);return aFib[n];}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;}


 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 西安儿童医院网上挂号预约 安徽省立医院预约挂号 重庆儿童医院预约挂号 南京儿童医院预约挂号 郑大一附院预约挂号网 济宁附属医院预约挂号 湘雅二医院预约挂号 怎样在网上预约医院挂号 就医160网上预约挂号 天津市总医院预约挂号平台 绵阳中心医院预约挂号系统 朝阳医院网上预约挂号 东莞人民医院预约挂号 广州中山二院预约挂号 南昌一附医院预约挂号 常州中医院预约挂号 杭州市中医院预约挂号 天津骨科医院预约挂号 积水潭网上预约挂号 武汉一医院网上预约挂号 怎么在网上预约挂号医院 保定省医院预约挂号 福建医护网预约挂号 第一人民医院网上挂号 珠海人民医院预约挂号 苏州中医院预约挂号 北京积水潭医院挂号 广州市统一预约挂号系统 无锡四院网上预约挂号 芜湖中医院预约挂号 青岛中心医院预约挂号 武汉中医院网上挂号 茂名人民医院预约挂号 广州市统一预约挂号平台 北京市统一预约挂号平台 苏州中医院网上挂号 深圳市160网上预约挂号 深圳160就医网预约挂号 珠海中医院预约挂号 青岛海慈医院预约挂号 第一医院网上预约挂号