【动态规划】Fibonacci, Shortest Paths

2018-05-06  本文已影响0人  flowerAO

connect dots ...

Part one

basic concepts

Fibonacci

problems:

F1 = F2 = 1
Fn = Fn-1 + Fn-2
Goal: compute Fn

Naive recursive algorithms

fib(n):
  if n <= 2: f = 1
  else: f = fib(n-1) + fib(n+2)
  return f

Memoized DP algorithm

memo = {}
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
  return f

Bottom-up DP algorithm

fib = {}
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]

shortest paths

problems:

δ(s, v)∀v

tool:

Guessing, a very powerful tool.a tried and tested method for solving any problem

There are some incoming edges to vertex v. The shortest path to v comes through one of those edges. We don't know which one. So before solving the problem of finding shortest path to v we have solve smaller problems of finding shortest path to the parent vertices. If we have 2 incoming edges u1 -> v and u2 -> v, then we have to first find the shortest paths to vertices u1 and u2. Once we know them we can choose one edge between u1 -> v and u2 -> v which will result in the shortest path to v.

guessing & DAG view

DAGS cyclic graph Shortest Paths Memoized Fibonacci DAG

遗留

PS

因为教授是自己非常喜欢的一位导师,他总是能够用轻松自如的态度和浅显的语言表述来授课,但记录到一半的时候会怀疑自己投入大量时间来这样做的价值。——毕竟还有很多事情需要去做。
到底是会做dp的题就OK了,还是细细解剖每一个细节,争取得到比DP本身更多的东西?比如思维方式,比如逻辑推理,比如面对一般性的问题如何去处理,又比如智慧本身。
再记录更多的时候,会得到一种喜悦。可以通过模仿,可以通过不断演练,都可以。其他需要我去做的事情皆黯淡无光。此时此刻,聚光灯,打在舞台正中央,打在我身上。

上一篇下一篇

猜你喜欢

热点阅读