Download presentation

Presentation is loading. Please wait.

Published byBrittney Farmer Modified about 1 year ago

1
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; ……..

2
Calculating F i Option(1) --Directly implement Recursion int fib(int n) int f 1,, f 2, f If(n < 2) f = n; else f 1 = fib(n-1) i f 2 = fib(n-2) i f = f 1 + f 2i f = f I very inefficient : how many calls ? For example: for f 6 ?

3
Dynamic programming / Fibonacci numbers Call structure of Recursion

4
Contd.. Very efficient: runtime at least (2 n/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 2 n/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 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;

Similar presentations

© 2016 SlidePlayer.com Inc.

All rights reserved.

Ads by Google