1 / 8

Dynamic Programming

Dynamic Programming. Fibonacci numbers-example- Defined by Recursion F 0 = 0 F 1 = 1 F n = F n-1 + F n-2 n >= 2 F 2 = 0+1; F 3 = 1+1 =2; F 4 = 1+2 = 3 F 5 = 2+3 = 5; ……. Calculating F i. Option(1) --Directly implement Recursion

vanig
Download Presentation

Dynamic Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Dynamic Programming • Fibonacci numbers-example- Defined by Recursion F0 = 0 F1 = 1 F n = Fn-1 + F n-2 n >= 2 F2 = 0+1; F3 = 1+1 =2; F 4= 1+2 = 3 F5 = 2+3 = 5; ……..

  2. Calculating Fi Option(1) --Directly implement Recursion int fib(int n) int f1,, f2 , f If(n < 2) f = n; else f1 = fib(n-1)i f2 = fib(n-2)i f = f 1+ f2i f = f I  very inefficient : how many calls ? For example: for f6 ?

  3. Dynamic programming / Fibonacci numbers • Call structure of Recursion

  4. Contd.. • Very efficient: runtime at least (2n/2) calculates the same numbers several times. IMPROVE: --- save previous results in a memory and recall when needed. (n) calls Full Binary Tree at least to depth n/2  2n/2 nodes. recall computed values f[0] = 0; f[1] = 1; for (i=2; i< = n; i++) f[i] = f[i-1] + f[i-2];

  5. Dynamic Programming Sub problem Graph • Decompose the main problem into smaller sub problems of the same kind. • Solve smaller problems recursively  save the intermediate solution. • Combine the solutions.

  6. Sub problem Graph -- vertices are : instances -- Directed edge : 1  3 1 directly calls 7 6 5 4 3 2 1 0 Structure of calls

  7. Contd.. • we can try to calculate in advance those instances which are needed for a given solution. • Those are exactly the nodes which are reachable from a given starting state(S). • The Depth-First search tree of the sub problem graph gives exactly those nodes which are reachable from S  perform dfs  get reachable nodes  Calculate sub problems and record solutions to dictionary solution.

  8. Dynamic programming version of the Fibonacci function. Example 10.3 fibDPwrap(n) Dict soln = create(n); return fibDP(soln, n); fibDP(soln, k) int fib, f1, f2; If(k<2) fib = k; else if(member(soln, k-1) = = false) f1 = fibDP(soln, k-1); else f1 = retrieve(soln, k-1); if(member(soln, k-2) = = false) f2 = fibDP(soln, k-2); else f2 = retrieve(soln, k-2); fib = f1 + f2; Store(soln, k, fib); return fib;

More Related