我的第一个动态规划程序(试图用递归求斐波拉契数)
2012-04-07 14:31
363 查看
1、这是一般的递归(指数爆炸型,时间复杂度O(1.618^n)):
2、今天看了动态规划的入门,觉得建备忘表的方法挺不错的,也是符合人的思维的(这很重要),于是就类比,写了带备忘表的递归求斐波拉契数,这应该是以空间换时间吧,备忘表是全局的,一但建起,之后的就好办了。
这是我学习动态规划的第一个应用,纪念一下!虽然还没充分体现动态规划(求最优解)的魅力。继续学习中。。。
2012/4/8 更新
原来这种方法叫 搜索+动态规划,顺便简化了第二个程序:
2012/5/11 更新
通项公式法,时空复杂度都是O(1)
#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; }
相关文章推荐
- 我的第一个动态规划程序(试图用递归求斐波拉契数)
- 我的第一个动态规划程序(试图用递归求斐波拉契数)
- 动态规划问题数字三角形的(递归程序)
- 动态规划(Dynamic programming,DP),通过把原问题分,为此动态规划法试图仅仅解决每个子问题一次,从而减少计算量:
- CrackingtheCodeInterview之递归和动态规划
- 格子取数问题的动态规划和递归解法之比较
- 动态规划,递归与非递归,FP 之野望,描述与计算
- [原]POJ1141 Brackets Sequence (dp动态规划,递归)
- POJ 1579 解法二用动态规划给递归剪枝,减少重复计算。此题一开始没想到用此法耗费了不少时间。
- 挑战程序竞赛系列(63):4.7字符串上的动态规划(1)
- 最长公共子序列求解:递归与动态规划方法
- 动态规划学习之三种方法解决斐波拉契数
- 剑指offer 07-10 斐波那契数列类型题目的动态规划解题方法(递归方法)
- 干净win7要做几步才能运行第一个Spring MVC 写的动态web程序
- 动态规划学习之三种方法解决斐波拉契数
- 动态规划(二)暴力递归的优化之路——数字三角形最大路径和
- 递归与动态规划关系
- 动态规划和递归
- 最长公共子序列求解:递归与动态规划方法
- 动态规划和递归、循环、迭代