SlideShare a Scribd company logo
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

PPTX
unit-4-dynamic programming
PPT
5.3 dynamic programming 03
DOC
Unit 3 daa
PPTX
Dynamic programming - fundamentals review
PPTX
Dynamic Programming - Part II
PDF
PPT
Branch and bound
PPTX
Dynamic programming1
unit-4-dynamic programming
5.3 dynamic programming 03
Unit 3 daa
Dynamic programming - fundamentals review
Dynamic Programming - Part II
Branch and bound
Dynamic programming1

What's hot (20)

PPTX
Dynamic Programming
PPTX
Matrix chain multiplication
PPTX
Greedy Algorithms
PPT
Analysis of Algorithm
PPT
Dynamic programming
PPT
dynamic programming Rod cutting class
PPTX
PPTX
Daa unit 3
PPTX
Dynamic Programming - Part 1
PPT
5.3 dynamic programming
PDF
Backtracking & branch and bound
PPT
5.1 greedy
PPT
Dynamicpgmming
PDF
Dynamic programming
PPT
Lecture 8 dynamic programming
PPTX
Daa:Dynamic Programing
PPT
5.1 greedy 03
PPTX
Comparitive Analysis of Algorithm strategies
PDF
Dynamic programming
Dynamic Programming
Matrix chain multiplication
Greedy Algorithms
Analysis of Algorithm
Dynamic programming
dynamic programming Rod cutting class
Daa unit 3
Dynamic Programming - Part 1
5.3 dynamic programming
Backtracking & branch and bound
5.1 greedy
Dynamicpgmming
Dynamic programming
Lecture 8 dynamic programming
Daa:Dynamic Programing
5.1 greedy 03
Comparitive Analysis of Algorithm strategies
Dynamic programming
Ad

Viewers also liked (10)

PPTX
Dynamic programming
PPT
lecture 23
PPTX
Longest Common Subsequence
PPT
lecture 24
PPTX
Longest common subsequence lcs
PPT
Dynamic pgmming
PPTX
Elements of dynamic programming
PPTX
Longest Common Subsequence (LCS) Algorithm
PPTX
Knapsack Problem
Dynamic programming
lecture 23
Longest Common Subsequence
lecture 24
Longest common subsequence lcs
Dynamic pgmming
Elements of dynamic programming
Longest Common Subsequence (LCS) Algorithm
Knapsack Problem
Ad

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

PPT
PDF
Sienna 10 dynamic
PPT
tutorial5.ppt
KEY
Presentation 3
PDF
Algorithm chapter 8
PPT
3. Recursion and Recurrences.ppt detail about recursive learning
PDF
Sure interview algorithm-1103
PDF
Dynamic programing
PPT
d0a2de03-27d3-4ca2-9ac6-d83440657a6c.ppt
PDF
DS & Algo 6 - Dynamic Programming
PDF
815.07 machine learning using python.pdf
PPT
Fibonacci
PPTX
Recursive Definitions in Discrete Mathmatcs.pptx
PPT
Lec-32 Recursion -Recursion in Computer Science
PPTX
PPTX
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
PDF
Copy of y16 02-2119divide-and-conquer
PPTX
Recursion
PPTX
Recursion DM
PPT
Lecture in Sets, Sequences and Summations
Sienna 10 dynamic
tutorial5.ppt
Presentation 3
Algorithm chapter 8
3. Recursion and Recurrences.ppt detail about recursive learning
Sure interview algorithm-1103
Dynamic programing
d0a2de03-27d3-4ca2-9ac6-d83440657a6c.ppt
DS & Algo 6 - Dynamic Programming
815.07 machine learning using python.pdf
Fibonacci
Recursive Definitions in Discrete Mathmatcs.pptx
Lec-32 Recursion -Recursion in Computer Science
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
Copy of y16 02-2119divide-and-conquer
Recursion
Recursion DM
Lecture in Sets, Sequences and Summations

More from zukun (20)

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

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
KodekX | Application Modernization Development
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Sensors and Actuators in IoT Systems using pdf
Spectral efficient network and resource selection model in 5G networks
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Advanced Soft Computing BINUS July 2025.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
The Rise and Fall of 3GPP – Time for a Sabbatical?
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 2 Digital Image Fundamentals.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Dropbox Q2 2025 Financial Results & Investor Presentation
GamePlan Trading System Review: Professional Trader's Honest Take
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
KodekX | Application Modernization Development
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
20250228 LYD VKU AI Blended-Learning.pptx
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
“AI and Expert System Decision Support & Business Intelligence Systems”
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Sensors and Actuators in IoT Systems using pdf

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.