SlideShare a Scribd company logo
4
Most read
6
Most read
8
Most read
Lecture 16:
Introduction to Dynamic Programming
            Steven Skiena

   Department of Computer Science
    State University of New York
    Stony Brook, NY 11794–4400

   http://www.cs.sunysb.edu/∼skiena
Problem of the Day
Multisets are allowed to have repeated elements. A multiset
of n items may thus have fewer than n! distinct permutations.
For example, {1, 1, 2, 2} has only six different permutations:
{1, 1, 2, 2}, {1, 2, 1, 2}, {1, 2, 2, 1}, {2, 1, 1, 2}, {2, 1, 2, 1},
and {2, 2, 1, 1}. Design and implement an efficient algorithm
for constructing all permutations of a multiset.
Dynamic Programming
Dynamic programming is a very powerful, general tool for
solving optimization problems on left-right-ordered items
such as character strings.
Once understood it is relatively easy to apply, it looks like
magic until you have seen enough examples.
Floyd’s all-pairs shortest-path algorithm was an example of
dynamic programming.
Greedy vs. Exhaustive Search
Greedy algorithms focus on making the best local choice at
each decision point. In the absence of a correctness proof
such greedy algorithms are very likely to fail.
Dynamic programming gives us a way to design custom
algorithms which systematically search all possibilities (thus
guaranteeing correctness) while storing results to avoid
recomputing (thus providing efficiency).
Recurrence Relations
A recurrence relation is an equation which is defined in terms
of itself. They are useful because many natural functions are
easily expressed as recurrences:
Polynomials: an = an−1 + 1, a1 = 1 −→ an = n
Exponentials: an = 2an−1 , a1 = 2 −→ an = 2n
Weird: an = nan−1 , a1 = 1 −→ an = n!
Computer programs can easily evaluate the value of a given
recurrence even without the existence of a nice closed form.
Computing Fibonacci Numbers

             Fn = Fn−1 + Fn−2, F0 = 0, F1 = 1
Implementing this as a recursive procedure is easy, but slow
because we keep calculating the same value over and over.
                                                   F(6)=13


                                        F(5)                                          F(4)


                              F(4)                     F(3)                   F(3)           F(2)


                                               F(2)          F(1)      F(2)       F(1) F(1)     F(0)
                      F(3)           F(2)

               F(2)       F(1) F(1)                                 F(1)   F(0)
                                       F(0) F(1)     F(0)


            F(1)   F(0)
How Slow?
                                √
          Fn+1/Fn ≈ φ = (1 +        5)/2 ≈ 1.61803
Thus Fn ≈ 1.6n .
Since our recursion tree has 0 and 1 as leaves, computing Fn
requires ≈ 1.6n calls!
What about Dynamic Programming?
We can calculate Fn in linear time by storing small values:
F0 = 0
F1 = 1
For i = 1 to n
      Fi = Fi−1 + Fi−2
Moral: we traded space for time.
Why I Love Dynamic Programming
Dynamic programming is a technique for efficiently comput-
ing recurrences by storing partial results.
Once you understand dynamic programming, it is usually
easier to reinvent certain algorithms than try to look them up!
I have found dynamic programming to be one of the most
useful algorithmic techniques in practice:
 • Morphing in computer graphics.
 • Data compression for high density bar codes.
 • Designing genes to avoid or contain specified patterns.
Avoiding Recomputation by Storing Partial
Results
The trick to dynamic program is to see that the naive recursive
algorithm repeatedly computes the same subproblems over
and over and over again. If so, storing the answers to them
in a table instead of recomputing can lead to an efficient
algorithm.
Thus we must first hunt for a correct recursive algorithm –
later we can worry about speeding it up by using a results
matrix.
Binomial Coefficients
The most important class of counting numbers are the
binomial coefficients, where ( ) counts the number of ways
                               n
                               k

to choose k things out of n possibilities.
 • Committees – How many ways are there to form a k-
   member committee from n people? By definition, ( ). n
                                                      k



 • Paths Across a Grid – How many ways are there to travel
   from the upper-left corner of an n × m grid to the lower-
   right corner by walking only down and to the right? Every
   path must consist of n + m steps, n downward and m to
   the right, so there are ( ) such sets/paths.
                         n+m
                          n
Computing Binomial Coefficients
Since ( ) = n!/((n − k)!k!), in principle you can compute
       n
       k

them straight from factorials.
However, intermediate calculations can easily cause arith-
metic overflow even when the final coefficient fits comfort-
ably within an integer.
Pascal’s Triangle
No doubt you played with this arrangement of numbers in
high school. Each number is the sum of the two numbers
directly above it:
      1
     11
    121
  1331
 14641
1 5 10 10 5 1
Pascal’s Recurrence
A more stable way to compute binomial coefficients is using
the recurrence relation implicit in the construction of Pascal’s
triangle, namely, that
                          ()=( )+( )
                          n
                          k
                              n−1
                              k−1
                                     n−1
                                      k



It works because the nth element either appears or does not
appear in one of the ( ) subsets of k elements.
                      n
                      k
Basis Case
No recurrence is complete without basis cases.
How many ways are there to choose 0 things from a set?
Exactly one, the empty set.
The right term of the sum drives us up to ( ). How many ways
                                        k
                                        k

are there to choose k things from a k-element set? Exactly
one, the complete set.
Binomial Coefficients Implementation

long binomial coefficient(n,m)
int n,m; (* compute n choose m *)
{
       int i,j; (* counters *)
       long bc[MAXN][MAXN]; (* table of binomial coefficients *)

     for (i=0; i<=n; i++) bc[i][0] = 1;

     for (j=0; j<=n; j++) bc[j][j] = 1;

     for (i=1; i<=n; i++)
     for (j=1; j<i; j++)
            bc[i][j] = bc[i-1][j-1] + bc[i-1][j];

     return( bc[n][m] );
}
Three Steps to Dynamic Programming

1. Formulate the answer as a recurrence relation or recursive
   algorithm.
2. Show that the number of different instances of your
   recurrence is bounded by a polynomial.
3. Specify an order of evaluation for the recurrence so you
   always have what you need.

More Related Content

What's hot (20)

Dynamic Programming
Dynamic Programming
Sahil Kumar
 
Matrix chain multiplication
Matrix chain multiplication
Respa Peter
 
Greedy Algorithms
Greedy Algorithms
Amrinder Arora
 
Analysis of Algorithm
Analysis of Algorithm
أحلام انصارى
 
Dynamic programming
Dynamic programming
Gopi Saiteja
 
dynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
DS ppt
DS ppt
kirupasuchi1996
 
Daa unit 3
Daa unit 3
Abhimanyu Mishra
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1
Amrinder Arora
 
5.3 dynamic programming
5.3 dynamic programming
Krish_ver2
 
Backtracking & branch and bound
Backtracking & branch and bound
Vipul Chauhan
 
5.1 greedy
5.1 greedy
Krish_ver2
 
Dynamicpgmming
Dynamicpgmming
Muhammad Wasif
 
Dynamic programming
Dynamic programming
Jay Nagar
 
Lecture 8 dynamic programming
Lecture 8 dynamic programming
Oye Tu
 
Daa:Dynamic Programing
Daa:Dynamic Programing
rupali_2bonde
 
5.1 greedy 03
5.1 greedy 03
Krish_ver2
 
Comparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategies
Talha Shaikh
 
Unit 3
Unit 3
Gunasundari Selvaraj
 
Dynamic programming
Dynamic programming
Amit Kumar Rathi
 
Dynamic Programming
Dynamic Programming
Sahil Kumar
 
Matrix chain multiplication
Matrix chain multiplication
Respa Peter
 
Dynamic programming
Dynamic programming
Gopi Saiteja
 
dynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1
Amrinder Arora
 
5.3 dynamic programming
5.3 dynamic programming
Krish_ver2
 
Backtracking & branch and bound
Backtracking & branch and bound
Vipul Chauhan
 
Dynamic programming
Dynamic programming
Jay Nagar
 
Lecture 8 dynamic programming
Lecture 8 dynamic programming
Oye Tu
 
Daa:Dynamic Programing
Daa:Dynamic Programing
rupali_2bonde
 
Comparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategies
Talha Shaikh
 

Viewers also liked (10)

Dynamic programming
Dynamic programming
Melaku Bayih Demessie
 
Dynamic programming lcs
Dynamic programming lcs
Department of Information Management Ming Chuan University, Taiwan
 
lecture 23
lecture 23
sajinsc
 
Longest Common Subsequence
Longest Common Subsequence
Swati Swati
 
lecture 24
lecture 24
sajinsc
 
Longest common subsequence lcs
Longest common subsequence lcs
Shahariar Rabby
 
Dynamic pgmming
Dynamic pgmming
Dr. C.V. Suresh Babu
 
Elements of dynamic programming
Elements of dynamic programming
Tafhim Islam
 
Longest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) Algorithm
Darshit Metaliya
 
Knapsack Problem
Knapsack Problem
Jenny Galino
 
Ad

Similar to Skiena algorithm 2007 lecture16 introduction to dynamic programming (20)

L16
L16
FALLEE31188
 
Sienna 10 dynamic
Sienna 10 dynamic
chidabdu
 
tutorial5.ppt
tutorial5.ppt
jvjfvvoa
 
Presentation 3
Presentation 3
KeatonTech
 
Algorithm chapter 8
Algorithm chapter 8
chidabdu
 
3. Recursion and Recurrences.ppt detail about recursive learning
3. Recursion and Recurrences.ppt detail about recursive learning
KashifNadeem52
 
Sure interview algorithm-1103
Sure interview algorithm-1103
Sure Interview
 
Dynamic programing
Dynamic programing
AniketSingh609353
 
d0a2de03-27d3-4ca2-9ac6-d83440657a6c.ppt
d0a2de03-27d3-4ca2-9ac6-d83440657a6c.ppt
SrishaUrala
 
DS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic Programming
Mohammad Imam Hossain
 
815.07 machine learning using python.pdf
815.07 machine learning using python.pdf
SairaAtta5
 
Fibonacci
Fibonacci
Tabarnac Maria
 
Recursive Definitions in Discrete Mathmatcs.pptx
Recursive Definitions in Discrete Mathmatcs.pptx
gbikorno
 
Lec-32 Recursion -Recursion in Computer Science
Lec-32 Recursion -Recursion in Computer Science
Anil Yadav
 
Recursion
Recursion
Kasun Ranga Wijeweera
 
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
allyn joy calcaben
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquer
Joepang2015
 
Recursion
Recursion
Abdur Rehman
 
Recursion DM
Recursion DM
Rokonuzzaman Rony
 
Lecture in Sets, Sequences and Summations
Lecture in Sets, Sequences and Summations
Kamal El-Saady
 
Sienna 10 dynamic
Sienna 10 dynamic
chidabdu
 
tutorial5.ppt
tutorial5.ppt
jvjfvvoa
 
Presentation 3
Presentation 3
KeatonTech
 
Algorithm chapter 8
Algorithm chapter 8
chidabdu
 
3. Recursion and Recurrences.ppt detail about recursive learning
3. Recursion and Recurrences.ppt detail about recursive learning
KashifNadeem52
 
Sure interview algorithm-1103
Sure interview algorithm-1103
Sure Interview
 
d0a2de03-27d3-4ca2-9ac6-d83440657a6c.ppt
d0a2de03-27d3-4ca2-9ac6-d83440657a6c.ppt
SrishaUrala
 
815.07 machine learning using python.pdf
815.07 machine learning using python.pdf
SairaAtta5
 
Recursive Definitions in Discrete Mathmatcs.pptx
Recursive Definitions in Discrete Mathmatcs.pptx
gbikorno
 
Lec-32 Recursion -Recursion in Computer Science
Lec-32 Recursion -Recursion in Computer Science
Anil Yadav
 
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
allyn joy calcaben
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquer
Joepang2015
 
Lecture in Sets, Sequences and Summations
Lecture in Sets, Sequences and Summations
Kamal El-Saady
 
Ad

More from zukun (20)

My lyn tutorial 2009
My lyn tutorial 2009
zukun
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCV
zukun
 
ETHZ CV2012: Information
ETHZ CV2012: Information
zukun
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statistics
zukun
 
Lecture9 camera calibration
Lecture9 camera calibration
zukun
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer vision
zukun
 
Modern features-part-4-evaluation
Modern features-part-4-evaluation
zukun
 
Modern features-part-3-software
Modern features-part-3-software
zukun
 
Modern features-part-2-descriptors
Modern features-part-2-descriptors
zukun
 
Modern features-part-1-detectors
Modern features-part-1-detectors
zukun
 
Modern features-part-0-intro
Modern features-part-0-intro
zukun
 
Lecture 02 internet video search
Lecture 02 internet video search
zukun
 
Lecture 01 internet video search
Lecture 01 internet video search
zukun
 
Lecture 03 internet video search
Lecture 03 internet video search
zukun
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learning
zukun
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer vision
zukun
 
Gephi tutorial: quick start
Gephi tutorial: quick start
zukun
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysis
zukun
 
Object recognition with pictorial structures
Object recognition with pictorial structures
zukun
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities
zukun
 
My lyn tutorial 2009
My lyn tutorial 2009
zukun
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCV
zukun
 
ETHZ CV2012: Information
ETHZ CV2012: Information
zukun
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statistics
zukun
 
Lecture9 camera calibration
Lecture9 camera calibration
zukun
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer vision
zukun
 
Modern features-part-4-evaluation
Modern features-part-4-evaluation
zukun
 
Modern features-part-3-software
Modern features-part-3-software
zukun
 
Modern features-part-2-descriptors
Modern features-part-2-descriptors
zukun
 
Modern features-part-1-detectors
Modern features-part-1-detectors
zukun
 
Modern features-part-0-intro
Modern features-part-0-intro
zukun
 
Lecture 02 internet video search
Lecture 02 internet video search
zukun
 
Lecture 01 internet video search
Lecture 01 internet video search
zukun
 
Lecture 03 internet video search
Lecture 03 internet video search
zukun
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learning
zukun
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer vision
zukun
 
Gephi tutorial: quick start
Gephi tutorial: quick start
zukun
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysis
zukun
 
Object recognition with pictorial structures
Object recognition with pictorial structures
zukun
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities
zukun
 

Recently uploaded (20)

Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 

Skiena algorithm 2007 lecture16 introduction to dynamic programming

  • 1. Lecture 16: Introduction to Dynamic Programming Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794–4400 http://www.cs.sunysb.edu/∼skiena
  • 2. Problem of the Day Multisets are allowed to have repeated elements. A multiset of n items may thus have fewer than n! distinct permutations. For example, {1, 1, 2, 2} has only six different permutations: {1, 1, 2, 2}, {1, 2, 1, 2}, {1, 2, 2, 1}, {2, 1, 1, 2}, {2, 1, 2, 1}, and {2, 2, 1, 1}. Design and implement an efficient algorithm for constructing all permutations of a multiset.
  • 3. Dynamic Programming Dynamic programming is a very powerful, general tool for solving optimization problems on left-right-ordered items such as character strings. Once understood it is relatively easy to apply, it looks like magic until you have seen enough examples. Floyd’s all-pairs shortest-path algorithm was an example of dynamic programming.
  • 4. Greedy vs. Exhaustive Search Greedy algorithms focus on making the best local choice at each decision point. In the absence of a correctness proof such greedy algorithms are very likely to fail. Dynamic programming gives us a way to design custom algorithms which systematically search all possibilities (thus guaranteeing correctness) while storing results to avoid recomputing (thus providing efficiency).
  • 5. Recurrence Relations A recurrence relation is an equation which is defined in terms of itself. They are useful because many natural functions are easily expressed as recurrences: Polynomials: an = an−1 + 1, a1 = 1 −→ an = n Exponentials: an = 2an−1 , a1 = 2 −→ an = 2n Weird: an = nan−1 , a1 = 1 −→ an = n! Computer programs can easily evaluate the value of a given recurrence even without the existence of a nice closed form.
  • 6. Computing Fibonacci Numbers Fn = Fn−1 + Fn−2, F0 = 0, F1 = 1 Implementing this as a recursive procedure is easy, but slow because we keep calculating the same value over and over. F(6)=13 F(5) F(4) F(4) F(3) F(3) F(2) F(2) F(1) F(2) F(1) F(1) F(0) F(3) F(2) F(2) F(1) F(1) F(1) F(0) F(0) F(1) F(0) F(1) F(0)
  • 7. How Slow? √ Fn+1/Fn ≈ φ = (1 + 5)/2 ≈ 1.61803 Thus Fn ≈ 1.6n . Since our recursion tree has 0 and 1 as leaves, computing Fn requires ≈ 1.6n calls!
  • 8. What about Dynamic Programming? We can calculate Fn in linear time by storing small values: F0 = 0 F1 = 1 For i = 1 to n Fi = Fi−1 + Fi−2 Moral: we traded space for time.
  • 9. Why I Love Dynamic Programming Dynamic programming is a technique for efficiently comput- ing recurrences by storing partial results. Once you understand dynamic programming, it is usually easier to reinvent certain algorithms than try to look them up! I have found dynamic programming to be one of the most useful algorithmic techniques in practice: • Morphing in computer graphics. • Data compression for high density bar codes. • Designing genes to avoid or contain specified patterns.
  • 10. Avoiding Recomputation by Storing Partial Results The trick to dynamic program is to see that the naive recursive algorithm repeatedly computes the same subproblems over and over and over again. If so, storing the answers to them in a table instead of recomputing can lead to an efficient algorithm. Thus we must first hunt for a correct recursive algorithm – later we can worry about speeding it up by using a results matrix.
  • 11. Binomial Coefficients The most important class of counting numbers are the binomial coefficients, where ( ) counts the number of ways n k to choose k things out of n possibilities. • Committees – How many ways are there to form a k- member committee from n people? By definition, ( ). n k • Paths Across a Grid – How many ways are there to travel from the upper-left corner of an n × m grid to the lower- right corner by walking only down and to the right? Every path must consist of n + m steps, n downward and m to the right, so there are ( ) such sets/paths. n+m n
  • 12. Computing Binomial Coefficients Since ( ) = n!/((n − k)!k!), in principle you can compute n k them straight from factorials. However, intermediate calculations can easily cause arith- metic overflow even when the final coefficient fits comfort- ably within an integer.
  • 13. Pascal’s Triangle No doubt you played with this arrangement of numbers in high school. Each number is the sum of the two numbers directly above it: 1 11 121 1331 14641 1 5 10 10 5 1
  • 14. Pascal’s Recurrence A more stable way to compute binomial coefficients is using the recurrence relation implicit in the construction of Pascal’s triangle, namely, that ()=( )+( ) n k n−1 k−1 n−1 k It works because the nth element either appears or does not appear in one of the ( ) subsets of k elements. n k
  • 15. Basis Case No recurrence is complete without basis cases. How many ways are there to choose 0 things from a set? Exactly one, the empty set. The right term of the sum drives us up to ( ). How many ways k k are there to choose k things from a k-element set? Exactly one, the complete set.
  • 16. Binomial Coefficients Implementation long binomial coefficient(n,m) int n,m; (* compute n choose m *) { int i,j; (* counters *) long bc[MAXN][MAXN]; (* table of binomial coefficients *) for (i=0; i<=n; i++) bc[i][0] = 1; for (j=0; j<=n; j++) bc[j][j] = 1; for (i=1; i<=n; i++) for (j=1; j<i; j++) bc[i][j] = bc[i-1][j-1] + bc[i-1][j]; return( bc[n][m] ); }
  • 17. Three Steps to Dynamic Programming 1. Formulate the answer as a recurrence relation or recursive algorithm. 2. Show that the number of different instances of your recurrence is bounded by a polynomial. 3. Specify an order of evaluation for the recurrence so you always have what you need.