博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Algorithm] Fibonacci problem by using Dynamic programming
阅读量:5094 次
发布时间:2019-06-13

本文共 2006 字,大约阅读时间需要 6 分钟。

vThere are three ways to solve Fibonacci problem

  1. Recursion
  2. Memoize
  3. Bottom-up

'First Recursion approach:

def fib(n):    if n == 1 or n == 2:        result = 1    else:        result = fib(n-1) + fib(n -2)        return result;

 

As we can see to calculate fib(5), we need to calculate fib(3) twice and fib(2) three times.

Time complexity is O(2^n), because for each n from 3, we need to call fib() twice in else block:

else:    result = fib(n-1) + fib(n -2)

 

To solve the problem, we can use memoize solution to solve repeated calculation.

deb fib(n, memo):    if memo[n] != null        return memo[n]    if n == 1 or n == 2:        result = 1    else:        result = fib(n - 1) + fib(n-2)    memo[n] = result    return result

Using fib(5) as example: to calulate fib(5) we need to know fib(4)..fib(3), fib(2), fib(1), since we already know fib(1), fib(2) = 1, then we can know fib(3) = 2..fib(4) = 3, fib(5) = 5. 

Time complexity is O(2n + 1) -> O(n): because we just need to go though memo once. And 2*2 is because of:

result = fib(n - 1) + fib(n-2)

We still can improve it by using bottom up approach, because from the previous solution:

Using fib(5) as example: to calulate fib(5) we need to know fib(4)..fib(3), fib(2), fib(1), since we already know fib(1), fib(2) = 1, then we can know fib(3) = 2..fib(4) = 3, fib(5) = 5. 

We can clear see the solution the problem by going from bottom (fib(1) & fib(2)) to up (fib(5)):

def fib_bottom_up(n):    if n == 1 or n == 2:        return 1    bottom_up = new int[n+1]    bottom_up[1] = 1    bottom_up[2] = 1    for i from 3 upto n:        bottom_up[i] = bottom_up[i-1]+bottom_up[i-2]    return bottom_up[n]

Time complexity is O(n).


 

Notice that some programming language has recursion limit, for example, python has set the limiation to 1000, which mean if you keep calling one function 1000 times, it will throw errors.

 

In this sense, bottom up is much better than recursion apporach (recursion and memoize).

转载于:https://www.cnblogs.com/Answer1215/p/10366741.html

你可能感兴趣的文章
java SE :标准输入/输出
查看>>
vs 打开项目时要建配置文件的解决办法
查看>>
sublimie 知乎
查看>>
three.js 入门案例
查看>>
一些方便系统诊断的bash函数
查看>>
Floyd算法 - 最短路径
查看>>
【转载】基于vw等viewport视区相对单位的响应式排版和布局
查看>>
<转>关于MFC的多线程类 CSemaphore,CMutex,CCriticalSection,CEvent
查看>>
《你们都是魔鬼吗》实验十二 团队作业八:Alpha冲刺
查看>>
jquery中ajax返回值无法传递到上层函数
查看>>
[Leetcode]942. DI String Match
查看>>
css3之transform-origin
查看>>
1003 Emergency
查看>>
bm25
查看>>
Oracle 导入导出 创建用户等
查看>>
Json,String,Map之间的转换
查看>>
深入剖析Android系统
查看>>
[转]JavaScript快速检测浏览器对CSS3特性的支持
查看>>
密码强度正则表达式 – 必须包含大写字母,小写字母和数字,至少8个字符等...
查看>>
对接系统的一些思考
查看>>