DP动态规划理解---入门之斐波那契数列

Talk is cheap, show me the code!

动态规划实在是太难啃了,前几天初步啃完了 递归,今天开始慢慢啃啃动态规划吧。

一个经典的问题:计算斐波那契数列,三种方法:

(1)递归

时间空间复杂度O(2^n)

(2)自上而下的动态规划,需要有一个mem数组来记住每个子问题

时间空间复杂度O(n)

(3)自下而上,不需要mem,迭代就好。

时间复杂度O(n); 空间复杂度O(1)

####Daynamic programming example Fib sequences:
# f(n)=f(n-1)+f(n-2); n=1 or n=0, f(n)=1

#The key idea of DP is memorize the saveld small problems!
#It's the improved version of recursion!
#So you need to understand recursion first!

#Method 1: simple recursion, you have to touch every leave everytime!
# you can imagine that the worst case of this method is a full binary tree.
# there would be 2^n leaves. So the time and space complexity of this method is O(2^n)!
def fib_recursion(n):
    if n == 0 or n == 1:
        return 1
    else:
        ret
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值