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 fib~fib once, each memo cost , the total is
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:
-
- subproblem needs to be acyclic, or will be infinite time
- cyclic -> acyclic