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