Download presentation

Presentation is loading. Please wait.

Published byBrittney Farmer Modified over 2 years 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 7 6543210 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

OK

递归算法的效率分析. When a function is called... A transfer of control occurs from the calling block to the code of the function --It is necessary that there be.

递归算法的效率分析. When a function is called... A transfer of control occurs from the calling block to the code of the function --It is necessary that there be.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt on vegetarian and non vegetarian relationships Ppt on basics of ms word 2007 View ppt on ipad Ppt on social reformers of india Ppt on human chromosomes diagram Ppt on limits and derivatives practice Slideshare ppt on stress management Ppt on instrument landing system cost Ppt on earth and space current Ppt on index numbers in business