MIT6.006 Note Dynamic Programming(1)

333 阅读1分钟

DP

  • like careful brtue force
  • dp = subproblem + 'reuse'

Case1 Fib

memorized version

fib(n)
	if n in memo: return memo[n]
    if n <= 2 f=1
    else f = fib(n-1) + fib(n-2)
    	 memo[n] = f // memorized call constant time
    return f;

the cost?

  • linear

if we use memorization we need to only calculate fib1_{1}~fibn_{n} once, each memo cost θ(1)\theta(1), the total is θ(n)\theta(n)

dict version

  • bottom-up fib
fib = {} // a dict
for k in range(1, n+1):
	if k <= 2 f =1
    else f = fib[k-1] + fib[k-2]
    fib[k] = f
return fib[n]
  • further step

delete the previous memo, put in the new one.

topological sort

Case2 Shortest Path

  • Shortest Path: δ(s,v)\delta(s,v)
  • δ(s,v)=min(δ(s,u))+w(u,v)\delta(s,v) = min(\delta(s,u)) + w(u,v)
  • subproblem needs to be acyclic, or will be infinite time
  • cyclic -> acyclic