SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
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.

Mais conteúdo relacionado

Mais procurados

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic ProgrammingSahil Kumar
 
Matrix chain multiplication
Matrix chain multiplicationMatrix chain multiplication
Matrix chain multiplicationRespa Peter
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingGopi Saiteja
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting classgiridaroori
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1Dynamic Programming - Part 1
Dynamic Programming - Part 1Amrinder Arora
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programmingKrish_ver2
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and boundVipul Chauhan
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingJay Nagar
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programmingOye Tu
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
Approximation algorithms
Approximation algorithmsApproximation algorithms
Approximation algorithmsGanesh Solanke
 
Comparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategiesComparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategiesTalha Shaikh
 

Mais procurados (20)

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Matrix chain multiplication
Matrix chain multiplicationMatrix chain multiplication
Matrix chain multiplication
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
Analysis of Algorithm
Analysis of AlgorithmAnalysis of Algorithm
Analysis of Algorithm
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
DS ppt
DS pptDS ppt
DS ppt
 
Daa unit 3
Daa unit 3Daa unit 3
Daa unit 3
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1Dynamic Programming - Part 1
Dynamic Programming - Part 1
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
 
5.1 greedy
5.1 greedy5.1 greedy
5.1 greedy
 
Dynamicpgmming
DynamicpgmmingDynamicpgmming
Dynamicpgmming
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Approximation algorithms
Approximation algorithmsApproximation algorithms
Approximation algorithms
 
5.1 greedy 03
5.1 greedy 035.1 greedy 03
5.1 greedy 03
 
Comparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategiesComparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategies
 
Unit 3
Unit 3Unit 3
Unit 3
 

Destaque (10)

Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Dynamic programming lcs
Dynamic programming lcsDynamic programming lcs
Dynamic programming lcs
 
lecture 23
lecture 23lecture 23
lecture 23
 
Longest Common Subsequence
Longest Common SubsequenceLongest Common Subsequence
Longest Common Subsequence
 
lecture 24
lecture 24lecture 24
lecture 24
 
Longest common subsequence lcs
Longest common subsequence  lcsLongest common subsequence  lcs
Longest common subsequence lcs
 
Dynamic pgmming
Dynamic pgmmingDynamic pgmming
Dynamic pgmming
 
Elements of dynamic programming
Elements of dynamic programmingElements of dynamic programming
Elements of dynamic programming
 
Longest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) AlgorithmLongest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) Algorithm
 
Knapsack Problem
Knapsack ProblemKnapsack Problem
Knapsack Problem
 

Semelhante a Skiena algorithm 2007 lecture16 introduction to dynamic programming

Semelhante a Skiena algorithm 2007 lecture16 introduction to dynamic programming (20)

Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Dynamic programing
Dynamic programingDynamic programing
Dynamic programing
 
tutorial5.ppt
tutorial5.ppttutorial5.ppt
tutorial5.ppt
 
Fibonacci using matlab
Fibonacci using matlabFibonacci using matlab
Fibonacci using matlab
 
Algorithms Design Homework Help
Algorithms Design Homework HelpAlgorithms Design Homework Help
Algorithms Design Homework Help
 
5 numerical analysis
5 numerical analysis5 numerical analysis
5 numerical analysis
 
Algorithms Design Exam Help
Algorithms Design Exam HelpAlgorithms Design Exam Help
Algorithms Design Exam Help
 
Skiena algorithm 2007 lecture18 application of dynamic programming
Skiena algorithm 2007 lecture18 application of dynamic programmingSkiena algorithm 2007 lecture18 application of dynamic programming
Skiena algorithm 2007 lecture18 application of dynamic programming
 
Computer Network Assignment Help
Computer Network Assignment HelpComputer Network Assignment Help
Computer Network Assignment Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Machine Learning
Machine LearningMachine Learning
Machine Learning
 
Mgm
MgmMgm
Mgm
 
Line Search Techniques by Fibonacci Search
Line Search Techniques by Fibonacci SearchLine Search Techniques by Fibonacci Search
Line Search Techniques by Fibonacci Search
 
Lagrange Interpolation
Lagrange InterpolationLagrange Interpolation
Lagrange Interpolation
 
AI Lesson 29
AI Lesson 29AI Lesson 29
AI Lesson 29
 
Lesson 29
Lesson 29Lesson 29
Lesson 29
 
Solution 3.
Solution 3.Solution 3.
Solution 3.
 
02 Notes Divide and Conquer
02 Notes Divide and Conquer02 Notes Divide and Conquer
02 Notes Divide and Conquer
 
Es272 ch5b
Es272 ch5bEs272 ch5b
Es272 ch5b
 
UMAP - Mathematics and implementational details
UMAP - Mathematics and implementational detailsUMAP - Mathematics and implementational details
UMAP - Mathematics and implementational details
 

Mais de zukun

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009zukun
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVzukun
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Informationzukun
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statisticszukun
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibrationzukun
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionzukun
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluationzukun
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-softwarezukun
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptorszukun
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectorszukun
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-introzukun
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video searchzukun
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video searchzukun
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video searchzukun
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learningzukun
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionzukun
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick startzukun
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysiszukun
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structureszukun
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities zukun
 

Mais de zukun (20)

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

Último

2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

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.