SlideShare a Scribd company logo
Dynamic Programming

Dr. C.V. Suresh Babu
Topics
 What

is Dynamic Programming
 Binomial Coefficient
 Floyd’s Algorithm
 Chained Matrix Multiplication
 Optimal Binary Search Tree
 Traveling Salesperson
2
Why Dynamic Programming?
 Divide-and-Conquer:

a top-down approach.
 Many smaller instances are computed more
than once.
 Dynamic

programming: a bottom-up approach.
 Solutions for smaller instances are stored in a
table for later use.
3
Dynamic Programming







An Algorithm Design Technique
A framework to solve Optimization problems
Elements of Dynamic Programming
Dynamic programming version of a recursive
algorithm.
Developing a Dynamic Programming Algorithm
–

Example: Multiplying a Sequence of Matrices

4
Why Dynamic Programming?
• It sometimes happens that the natural way of dividing an
instance suggested by the structure of the problem leads us to
consider several overlapping subinstances.
• If we solve each of these independently, they will in turn
create a large number of identical subinstances.
• If we pay no attention to this duplication, it is likely that we
will end up with an inefficient algorithm.
• If, on the other hand, we take advantage of the duplication and
solve each subinstance only once, saving the solution for later
use, then a more efficient algorithm will result.
5
Why Dynamic Programming? …
The underlying idea of dynamic programming is
thus quite simple: avoid calculating the same thing
twice, usually by keeping a table of known results,
which we fill up as subinstances are solved.
• Dynamic programming is a bottom-up technique.
• Examples:
1) Fibonacci numbers
2) Computing a Binomial coefficient
6
Dynamic Programming

• Dynamic Programming is a general algorithm design
technique.
• Invented by American mathematician Richard Bellman in
the 1950s to solve optimization problems.
• “Programming” here means “planning”.
• Main idea:
• solve several smaller (overlapping) subproblems.
• record solutions in a table so that each subproblem is
only solved once.
• final state of the table will be (or contain) solution. 7
Dynamic Programming
 Define

a container to store intermediate

results
 Access container versus recomputing results
 Fibonacci
–

numbers example (top down)

Use vector to store results as calculated so they
are not re-calculated
8
Dynamic Programming
 Fibonacci

numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 24

 Recurrence

Relation of Fibonacci numbers

?
9
Example: Fibonacci numbers
• Recall definition of Fibonacci numbers:
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2)

for n ≥ 2

• Computing the nth Fibonacci number recursively (topdown):
f(n)
f(n-1)
f(n-2)

+

+
f(n-3)

f(n-2)
f(n-3)

+

f(n-4)

10
Fib vs. fibDyn
int fib(int n) {
if (n <= 1)
return n; // stopping conditions
else return fib(n-1) + fib(n-2);
// recursive step
}
int fibDyn(int n, vector<int>& fibList) {
int fibValue;
if (fibList[n] >= 0) // check for a previously computed result and return
return fibList[n];
// otherwise execute the recursive algorithm to obtain the result
if (n <= 1)
// stopping conditions
fibValue = n;
else
// recursive step
fibValue = fibDyn(n-1, fibList) + fibDyn(n-2, fibList);
// store the result and return its value
fibList[n] = fibValue;
return fibValue;
}

11
Example: Fibonacci numbers
Computing the nth fibonacci number using bottom-up
iteration:
• f(0) = 0
• f(1) = 1
• f(2) = 0+1 = 1
• f(3) = 1+1 = 2
• f(4) = 1+2 = 3
• f(5) = 2+3 = 5
•
•
•
• f(n-2) = f(n-3)+f(n-4)
• f(n-1) = f(n-2)+f(n-3)
• f(n) = f(n-1) + f(n-2)

12
Recursive calls for fib(5)
f ib ( 5 )
f ib ( 3 )

f ib ( 4 )
f ib ( 3 )

f ib ( 2 )
f ib ( 1 )

f ib ( 2 )
f ib ( 1 )

f ib ( 1 )

f ib ( 1 )

f ib ( 2 )
f ib ( 0 )

f ib ( 1 )

f ib ( 0 )

f ib ( 0 )
13
fib(5) Using Dynamic Programming
f ib ( 5 )
6

f ib ( 4 )

f ib ( 3 )

5
f ib ( 3 )

f ib ( 2 )

f ib ( 1 )

f ib ( 2 )

4
f ib ( 2 )

f ib ( 1 )

f ib ( 1 )

f ib ( 0 )

f ib ( 1 )

f ib ( 0 )

3
f ib ( 1 )

f ib ( 0 )

1

2

14
Statistics (function calls)
fib

fibDyn

N = 20

21,891

39

N = 40

331,160,281

79

15
Top down vs. Bottom up
 Top

down dynamic programming moves
through recursive process and stores results
as algorithm computes
 Bottom up dynamic programming evaluates
by computing all function values in order,
starting at lowest and using previously
computed values.
16
Examples of Dynamic Programming Algorithms
• Computing binomial coefficients
• Optimal chain matrix multiplication
• Floyd’s algorithms for all-pairs shortest paths
• Constructing an optimal binary search tree
• Some instances of difficult discrete optimization problems:
• travelling salesman
• knapsack
17
A framework to solve Optimization problems
 For
–
–
–

each current choice:

Determine what subproblem(s) would remain if this
choice were made.
Recursively find the optimal costs of those
subproblems.
Combine those costs with the cost of the current
choice itself to obtain an overall cost for this choice

 Select

a current choice that produced the
minimum overall cost.
18
Elements of Dynamic Programming


Constructing solution to a problem by building it up
dynamically from solutions to smaller (or simpler) subproblems
–

–

sub-instances are combined to obtain sub-instances of
increasing size, until finally arriving at the solution of the
original instance.
make a choice at each step, but the choice may depend on the
solutions to sub-problems.

19
Elements of Dynamic Programming …



Principle of optimality
–



the optimal solution to any nontrivial instance of a problem is a
combination of optimal solutions to some of its sub-instances.

Memorization (for overlapping sub-problems)
–
–

avoid calculating the same thing twice,
usually by keeping a table of know results that fills up as subinstances are solved.

20
Development of a dynamic programming
algorithm








Characterize the structure of an optimal solution
– Breaking a problem into sub-problem
– whether principle of optimality apply
Recursively define the value of an optimal solution
– define the value of an optimal solution based on value of solutions
to sub-problems
Compute the value of an optimal solution in a bottom-up fashion
– compute in a bottom-up fashion and save the values along the
way
– later steps use the save values of pervious steps
Construct an optimal solution from computed information
21
Binomial Coefficient


Binomial coefficient:
n 
n!
 =
k  k!( n −k )!
 





for 0 ≤ k ≤ n

Cannot compute using this formula because of
n!
Instead, use the following formula:

22
Binomial Using Divide & Conquer


Binomial formula:

  n − 1   n − 1
C
 k − 1 + C  k  0 < k < n
 

 n  
 

C  = 
k
 n
 n
  
1
k = 0 or k = n (C   or C   )
 0
 n

 
 

23
Binomial using Dynamic Programming



Just like Fibonacci, that formula is very inefficient
Instead, we can use the following:

(a + b) n = C (n,0)a n + ... + C (n, i )a n −i b i + ... + C (n, n)b n

24
Bottom-Up
 Recursive
–

B[i] [j] =

property:
B[i – 1] [j – 1] + B[i – 1][j] 0 < j < i
1

j = 0 or j = i

25
Pascal’s Triangle
0

1

0

1

1

1

1

2

1

2

1

3

1

3

3 1

4

1

4

6 4

…
i
n

2

3 4

…

j

k

1
B[i-1][j-1]+ B[i-1][j]
B[i][j]
26
Binomial Coefficient


Record the values in a table of n+1 rows and k+1 columns

0

1

2

0

1
1

2

1

3

3

k

1

3

k-1

1

2

…

1

1

3

1

...
k

1

1

…
n-1

1

n

1

 n − 1
C
 k − 1




 n − 1
C
k 



n 
C 
k 
 

27
Binomial Coefficient
ALGORITHM Binomial(n,k)
//Computes C(n, k) by the dynamic programming algorithm
//Input: A pair of nonnegative integers n ≥ k ≥ 0
//Output: The value of C(n ,k)
for i 0 to n do
for j 0 to min (i ,k) do
if j = 0 or j = k
C [i , j]  1
else C [i , j]  C[i-1, j-1] + C[i-1, j]
return C [n, k]
k

i −1

A( n, k ) = ∑∑1 +
i =1 j =1

=

n

k

k

n

i =1

i =K +1

∑ ∑1 = ∑(i −1) + ∑k

i =k +1 j =1

( k −1) k
+ k ( n − k ) ∈Θ( nk )
2

28
Floyd’s Algorithm: All pairs shortest paths
•Find shortest path when direct path doesn’t exist
•In a weighted graph, find shortest paths between every pair of
vertices
• Same idea: construct solution through series of matrices
D(0), D(1), … using an initial subset of the vertices as
4
3
intermediaries.
1
• Example:
1
6
1

5

2

3

4

29
Shortest Path





Optimization problem – more than one candidate for
the solution
Solution is the candidate with optimal value
Solution 1 – brute force
–
–



Find all possible paths, compute minimum
Efficiency?
Worse than O(n2)

Solution 2 – dynamic programming
–
–

Algorithm that determines only lengths of shortest paths
Modify to produce shortest paths as well
30
Example
1

2

3

4

5

1

2

3

4

5

1

0

1

∞

1

5

1

0

1

3

1

4

2

9

0

3

2

∞

2

8

0

3

2

5

3

∞

∞

0

4

∞

3

10 11

0

4

7

4

∞

∞

2

0

3

4

6

7

2

0

3

5

3

∞

∞

∞

0

5

3

4

6

4

0

W - Graph in adjacency matrix

D - Floyd’s algorithm

31
Meanings









D(0)[2][5] = lenth[v2, v5]= ∞
D(1)[2][5] = minimum(length[v2,v5], length[v2,v1,v5])
= minimum (∞, 14) = 14
D(2)[2][5] = D(1)[2][5] = 14
D(3)[2][5] = D(2)[2][5] = 14
D(4)[2][5] = minimum(length[v2,v1,v5], length[v2,v4,v5]),
length[v2,v1,v5], length[v2, v3,v4,v5]),
= minimum (14, 5, 13, 10) = 5
D(5)[2][5] = D(4)[2][5] = 5
32
Floyd’s Algorithm
2

a

7

6

3

b

c

d
1

(
(
(
(
(
d ijk ) = min{d ijk −1) , d ikk −1) + d kjk −1) } for k ≥ 1, d ij0 ) = wij

33
Computing D
 D(0)

=W
 Now compute D(1)
 Then D(2)
 Etc.

34
Floyd’s Algorithm: All pairs shortest paths
• ALGORITHM Floyd (W[1 … n, 1… n])

•For k ← 1 to n do
•For i ← 1 to n do
•For j ← 1 to n do
•W[i, j] ← min{W[i,j], W{i, k] + W[k, j]}
•Return W
•Efficiency = ?

Θ(n)

35
Example: All-pairs shortest-path problem
Example: Apply Floyd’s algorithm to find the t Allpairs shortest-path problem of the digraph defined by
the following weight matrix
0
6
∞
∞
3

2
0
∞
∞
∞

∞
3
0
2
∞

1
2
4
0
∞

8
∞
∞
3
0

36
Visualizations




http://www.ifors.ms.unimelb.edu.au/tutorial/path/#list
http://www1.math.luc.edu/~dhardy/java/alg/floyd.html
http://students.ceid.upatras.gr/%7Epapagel/project/kef5_7_2.htm

37
Chained Matrix Multiplication


Problem: Matrix-chain multiplication
– a chain of <A1, A2, …, An> of n matrices
–






find a way that minimizes the number of scalar multiplications to
compute the product A1A2…An

Strategy:
Breaking a problem into sub-problem
– A1A2...Ak, Ak+1Ak+2…An
Recursively define the value of an optimal solution
– m[i,j] = 0 if i = j
– m[i,j]= min{i<=k<j} (m[i,k]+m[k+1,j]+pi-1pkpj)
–

for 1 <= i <= j <= n

38
Example
 Suppose

we want to multiply a 2x2 matrix
with a 3x4 matrix
 Result is a 2x4 matrix
 In general, an i x j matrix times a j x k matrix
requires i x j x k elementary multiplications

39
Example


Consider multiplication of four matrices:
A
(20 x 2)



x

B
(2 x 30)

x

C
(30 x 12)

x

D
(12 x 8)

Matrix multiplication is associative
A(B (CD)) = (AB) (CD)



Five different orders for multiplying 4 matrices
1.
2.
3.
4.
5.

A(B (CD)) = 30*12*8 + 2*30*8 + 20*2*3 = 3,680
(AB) (CD) = 20*2*30 + 30*12*8 + 20*30*8 = 8,880
A ((BC) D) = 2*30*12 + 2*12*3 + 20*2*8 = 1,232
((AB) C) D = 20*2*30 + 20*30*12 + 20*12*8 = 10,320
(A (BC)) D = 2*30*12 + 20*2*12 + 20*12*8 = 3,120
40
Algorithm
int minmult (int n, const ind d[], index P[ ] [ ])
{
index i, j, k, diagonal;
int M[1..n][1..n];
for (i = 1; i <= n; i++)
M[i][i] = 0;
for (diagonal = 1; diagonal <= n-1; diagonal++)
for (i = 1; i <= n-diagonal; i++)
{
j = i + diagonal;
M[i] [j] = minimum(M[i][k] + M[k+1][j] + d[i-1]*d[k]*d[j]);
// minimun (i <= k <= j-1)
P[i] [j] = a value of k that gave the minimum;
}
return M[1][n];
}

41
Optimal Binary Trees
 Optimal

way of constructing a binary search

tree
 Minimum depth, balanced (if all keys have
same probability of being the search key)
 What if probability is not all the same?
 Multiply probability of accessing that key by
number of links to get to that key
42
Example
If p1 = 0.7
Key3

p2 = 0.2

3(0.7) + 2(0.2) + 1(0.1)
= 2.6

p3 = 0.1
key2

Θ (n3) Efficiency

key1

43
Traveling Salesperson
 The

Traveling Salesman Problem (TSP) is a
deceptively simple combinatorial problem. It
can be stated very simply:
 A salesman spends his time visiting n cities
(or nodes) cyclically. In one tour he visits
each city just once, and finishes up where he
started. In what order should he visit them to
minimize the distance traveled?
44
Why study?






The problem has some direct importance, since
quite a lot of practical applications can be put in this
form.
It also has a theoretical importance in complexity
theory, since the TSP is one of the class of "NP
Complete" combinatorial problems.
NP Complete problems are intractable in the sense
that no one has found any really efficient way of
solving them for large n.
–

They are also known to be more or less equivalent to each
other; if you knew how to solve one kind of NP Complete
problem you could solve the lot.
45
Efficiency
 The

holy grail is to find a solution algorithm
that gives an optimal solution in a time that
has a polynomial variation with the size n of
the problem.
 The best that people have been able to do,
however, is to solve it in a time that varies
exponentially with n.
46
Later…
 We’ll

get back to the traveling salesperson
problem in the next chapter….

47
Animations
 http://www.pcug.org.au/~dakin/tsp.htm

 http://www.ing.unlp.edu.ar/cetad/mos/TSPBIB_hom

48
Chapter Summary
• Dynamic programming is similar to divide-andconquer.
• Dynamic programming is a bottom-up approach.
• Dynamic programming stores the results (small
instances) in the table and reuses it instead of
recomputing it.
• Two steps in development of a dynamic
programming algorithm:
• Establish a recursive property
• Solve an instance of the problem in a bottom-up 49
Exercise: Sudoku puzzle

50
Rules of Sudoku
• Place a number (1-9) in each blank cell.
• Each row (nine lines from left to right), column (also
nine lines from top to bottom) and 3x3 block bounded
by bold line (nine blocks) contains number from 1
through 9.

51

More Related Content

What's hot

Introduction to dynamic programming
Introduction to dynamic programmingIntroduction to dynamic programming
Introduction to dynamic programming
Amisha Narsingani
 
Traveling Salesman Problem
Traveling Salesman Problem Traveling Salesman Problem
Traveling Salesman Problem
Indian Institute of Technology, Roorkee
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
Krish_ver2
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
shashidharPapishetty
 
Travelling SalesMan Problem(TSP)
Travelling SalesMan Problem(TSP)Travelling SalesMan Problem(TSP)
Travelling SalesMan Problem(TSP)
Akshay Kamble
 
Np hard
Np hardNp hard
Np hard
jesal_joshi
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithm
HoneyChintal
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
Knapsack problem using greedy approach
Knapsack problem using greedy approachKnapsack problem using greedy approach
Knapsack problem using greedy approach
padmeshagrekar
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
Rajendran
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Shakil Ahmed
 
Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
Bhavin Darji
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest path
Arafat Hossan
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
Animesh Chaturvedi
 
N queen problem
N queen problemN queen problem
N queen problem
Ridhima Chowdhury
 
Matrix chain multiplication
Matrix chain multiplicationMatrix chain multiplication
Matrix chain multiplication
Respa Peter
 
Introduction to optimization Problems
Introduction to optimization ProblemsIntroduction to optimization Problems
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
ishmecse13
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Dr Shashikant Athawale
 
knapsack problem
knapsack problemknapsack problem
knapsack problem
Adnan Malak
 

What's hot (20)

Introduction to dynamic programming
Introduction to dynamic programmingIntroduction to dynamic programming
Introduction to dynamic programming
 
Traveling Salesman Problem
Traveling Salesman Problem Traveling Salesman Problem
Traveling Salesman Problem
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
 
Travelling SalesMan Problem(TSP)
Travelling SalesMan Problem(TSP)Travelling SalesMan Problem(TSP)
Travelling SalesMan Problem(TSP)
 
Np hard
Np hardNp hard
Np hard
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithm
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Knapsack problem using greedy approach
Knapsack problem using greedy approachKnapsack problem using greedy approach
Knapsack problem using greedy approach
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest path
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
 
N queen problem
N queen problemN queen problem
N queen problem
 
Matrix chain multiplication
Matrix chain multiplicationMatrix chain multiplication
Matrix chain multiplication
 
Introduction to optimization Problems
Introduction to optimization ProblemsIntroduction to optimization Problems
Introduction to optimization Problems
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
knapsack problem
knapsack problemknapsack problem
knapsack problem
 

Viewers also liked

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
Sahil Kumar
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programmingparamalways
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programmingOye Tu
 
Elements of dynamic programming
Elements of dynamic programmingElements of dynamic programming
Elements of dynamic programming
Tafhim Islam
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic ProgrammingNilam Kabra
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals review
ElifTech
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
Caisar Oentoro
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
Krish_ver2
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
contact2kazi
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
Amrinder Arora
 
Optimum polygon triangulation
Optimum polygon triangulationOptimum polygon triangulation
Optimum polygon triangulation
Harsukh Chandak
 
Combinatorial Optimization
Combinatorial OptimizationCombinatorial Optimization
Combinatorial Optimization
Institute of Technology, Nirma University
 
Dynamic programming
Dynamic programming Dynamic programming
Dynamic programming
Zohaib HUSSAIN
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
Rajendran
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
Muhammad Amjad Rana
 
Skiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingSkiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingzukun
 

Viewers also liked (20)

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Elements of dynamic programming
Elements of dynamic programmingElements of dynamic programming
Elements of dynamic programming
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals review
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
Knapsack Problem
Knapsack ProblemKnapsack Problem
Knapsack Problem
 
Optimum polygon triangulation
Optimum polygon triangulationOptimum polygon triangulation
Optimum polygon triangulation
 
Combinatorial Optimization
Combinatorial OptimizationCombinatorial Optimization
Combinatorial Optimization
 
Dynamic programming
Dynamic programming Dynamic programming
Dynamic programming
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
 
Np complete
Np completeNp complete
Np complete
 
Huffman Coding
Huffman CodingHuffman Coding
Huffman Coding
 
Huffman Coding
Huffman CodingHuffman Coding
Huffman Coding
 
Skiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingSkiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programming
 

Similar to Dynamic pgmming

dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
Solving Optimization Problems using the Matlab Optimization.docx
Solving Optimization Problems using the Matlab Optimization.docxSolving Optimization Problems using the Matlab Optimization.docx
Solving Optimization Problems using the Matlab Optimization.docx
whitneyleman54422
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdf
jannatulferdousmaish
 
Module 2ppt.pptx divid and conquer method
Module 2ppt.pptx divid and conquer methodModule 2ppt.pptx divid and conquer method
Module 2ppt.pptx divid and conquer method
JyoReddy9
 
Algorithm_Dynamic Programming
Algorithm_Dynamic ProgrammingAlgorithm_Dynamic Programming
Algorithm_Dynamic Programming
Im Rafid
 
Convex optmization in communications
Convex optmization in communicationsConvex optmization in communications
Convex optmization in communications
Deepshika Reddy
 
OI.ppt
OI.pptOI.ppt
OI.ppt
raj20072
 
dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)
Mumtaz Ali
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1Dynamic Programming - Part 1
Dynamic Programming - Part 1
Amrinder Arora
 
LPP, Duality and Game Theory
LPP, Duality and Game TheoryLPP, Duality and Game Theory
LPP, Duality and Game Theory
Purnima Pandit
 
Algorithms practice and problem solving - dynamic programming
Algorithms practice and problem solving - dynamic programmingAlgorithms practice and problem solving - dynamic programming
Algorithms practice and problem solving - dynamic programming
Xochitl Watts
 
Dynamic programming prasintation eaisy
Dynamic programming prasintation eaisyDynamic programming prasintation eaisy
Dynamic programming prasintation eaisy
ahmed51236
 
815.07 machine learning using python.pdf
815.07 machine learning using python.pdf815.07 machine learning using python.pdf
815.07 machine learning using python.pdf
SairaAtta5
 
Algorithm review
Algorithm reviewAlgorithm review
Algorithm reviewchidabdu
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Gopi Saiteja
 
Lecture11
Lecture11Lecture11
Lecture11
Nv Thejaswini
 
Balaji-opt-lecture6-act.ppt
Balaji-opt-lecture6-act.pptBalaji-opt-lecture6-act.ppt
Balaji-opt-lecture6-act.ppt
JamesGreen666883
 

Similar to Dynamic pgmming (20)

Dynamicpgmming
DynamicpgmmingDynamicpgmming
Dynamicpgmming
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
Solving Optimization Problems using the Matlab Optimization.docx
Solving Optimization Problems using the Matlab Optimization.docxSolving Optimization Problems using the Matlab Optimization.docx
Solving Optimization Problems using the Matlab Optimization.docx
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdf
 
Module 2ppt.pptx divid and conquer method
Module 2ppt.pptx divid and conquer methodModule 2ppt.pptx divid and conquer method
Module 2ppt.pptx divid and conquer method
 
Algorithm_Dynamic Programming
Algorithm_Dynamic ProgrammingAlgorithm_Dynamic Programming
Algorithm_Dynamic Programming
 
Convex optmization in communications
Convex optmization in communicationsConvex optmization in communications
Convex optmization in communications
 
OI.ppt
OI.pptOI.ppt
OI.ppt
 
dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1Dynamic Programming - Part 1
Dynamic Programming - Part 1
 
LPP, Duality and Game Theory
LPP, Duality and Game TheoryLPP, Duality and Game Theory
LPP, Duality and Game Theory
 
Algorithms practice and problem solving - dynamic programming
Algorithms practice and problem solving - dynamic programmingAlgorithms practice and problem solving - dynamic programming
Algorithms practice and problem solving - dynamic programming
 
Dynamic programming prasintation eaisy
Dynamic programming prasintation eaisyDynamic programming prasintation eaisy
Dynamic programming prasintation eaisy
 
815.07 machine learning using python.pdf
815.07 machine learning using python.pdf815.07 machine learning using python.pdf
815.07 machine learning using python.pdf
 
Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
LP.ppt
LP.pptLP.ppt
LP.ppt
 
Lecture11
Lecture11Lecture11
Lecture11
 
Balaji-opt-lecture6-act.ppt
Balaji-opt-lecture6-act.pptBalaji-opt-lecture6-act.ppt
Balaji-opt-lecture6-act.ppt
 

More from Dr. C.V. Suresh Babu

Data analytics with R
Data analytics with RData analytics with R
Data analytics with R
Dr. C.V. Suresh Babu
 
Association rules
Association rulesAssociation rules
Association rules
Dr. C.V. Suresh Babu
 
Clustering
ClusteringClustering
Classification
ClassificationClassification
Classification
Dr. C.V. Suresh Babu
 
Blue property assumptions.
Blue property assumptions.Blue property assumptions.
Blue property assumptions.
Dr. C.V. Suresh Babu
 
Introduction to regression
Introduction to regressionIntroduction to regression
Introduction to regression
Dr. C.V. Suresh Babu
 
DART
DARTDART
Mycin
MycinMycin
Expert systems
Expert systemsExpert systems
Expert systems
Dr. C.V. Suresh Babu
 
Dempster shafer theory
Dempster shafer theoryDempster shafer theory
Dempster shafer theory
Dr. C.V. Suresh Babu
 
Bayes network
Bayes networkBayes network
Bayes network
Dr. C.V. Suresh Babu
 
Bayes' theorem
Bayes' theoremBayes' theorem
Bayes' theorem
Dr. C.V. Suresh Babu
 
Knowledge based agents
Knowledge based agentsKnowledge based agents
Knowledge based agents
Dr. C.V. Suresh Babu
 
Rule based system
Rule based systemRule based system
Rule based system
Dr. C.V. Suresh Babu
 
Formal Logic in AI
Formal Logic in AIFormal Logic in AI
Formal Logic in AI
Dr. C.V. Suresh Babu
 
Production based system
Production based systemProduction based system
Production based system
Dr. C.V. Suresh Babu
 
Game playing in AI
Game playing in AIGame playing in AI
Game playing in AI
Dr. C.V. Suresh Babu
 
Diagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AIDiagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AI
Dr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
Dr. C.V. Suresh Babu
 

More from Dr. C.V. Suresh Babu (20)

Data analytics with R
Data analytics with RData analytics with R
Data analytics with R
 
Association rules
Association rulesAssociation rules
Association rules
 
Clustering
ClusteringClustering
Clustering
 
Classification
ClassificationClassification
Classification
 
Blue property assumptions.
Blue property assumptions.Blue property assumptions.
Blue property assumptions.
 
Introduction to regression
Introduction to regressionIntroduction to regression
Introduction to regression
 
DART
DARTDART
DART
 
Mycin
MycinMycin
Mycin
 
Expert systems
Expert systemsExpert systems
Expert systems
 
Dempster shafer theory
Dempster shafer theoryDempster shafer theory
Dempster shafer theory
 
Bayes network
Bayes networkBayes network
Bayes network
 
Bayes' theorem
Bayes' theoremBayes' theorem
Bayes' theorem
 
Knowledge based agents
Knowledge based agentsKnowledge based agents
Knowledge based agents
 
Rule based system
Rule based systemRule based system
Rule based system
 
Formal Logic in AI
Formal Logic in AIFormal Logic in AI
Formal Logic in AI
 
Production based system
Production based systemProduction based system
Production based system
 
Game playing in AI
Game playing in AIGame playing in AI
Game playing in AI
 
Diagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AIDiagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AI
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 

Recently uploaded

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 

Recently uploaded (20)

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 

Dynamic pgmming

  • 2. Topics  What is Dynamic Programming  Binomial Coefficient  Floyd’s Algorithm  Chained Matrix Multiplication  Optimal Binary Search Tree  Traveling Salesperson 2
  • 3. Why Dynamic Programming?  Divide-and-Conquer: a top-down approach.  Many smaller instances are computed more than once.  Dynamic programming: a bottom-up approach.  Solutions for smaller instances are stored in a table for later use. 3
  • 4. Dynamic Programming      An Algorithm Design Technique A framework to solve Optimization problems Elements of Dynamic Programming Dynamic programming version of a recursive algorithm. Developing a Dynamic Programming Algorithm – Example: Multiplying a Sequence of Matrices 4
  • 5. Why Dynamic Programming? • It sometimes happens that the natural way of dividing an instance suggested by the structure of the problem leads us to consider several overlapping subinstances. • If we solve each of these independently, they will in turn create a large number of identical subinstances. • If we pay no attention to this duplication, it is likely that we will end up with an inefficient algorithm. • If, on the other hand, we take advantage of the duplication and solve each subinstance only once, saving the solution for later use, then a more efficient algorithm will result. 5
  • 6. Why Dynamic Programming? … The underlying idea of dynamic programming is thus quite simple: avoid calculating the same thing twice, usually by keeping a table of known results, which we fill up as subinstances are solved. • Dynamic programming is a bottom-up technique. • Examples: 1) Fibonacci numbers 2) Computing a Binomial coefficient 6
  • 7. Dynamic Programming • Dynamic Programming is a general algorithm design technique. • Invented by American mathematician Richard Bellman in the 1950s to solve optimization problems. • “Programming” here means “planning”. • Main idea: • solve several smaller (overlapping) subproblems. • record solutions in a table so that each subproblem is only solved once. • final state of the table will be (or contain) solution. 7
  • 8. Dynamic Programming  Define a container to store intermediate results  Access container versus recomputing results  Fibonacci – numbers example (top down) Use vector to store results as calculated so they are not re-calculated 8
  • 9. Dynamic Programming  Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 24  Recurrence Relation of Fibonacci numbers ? 9
  • 10. Example: Fibonacci numbers • Recall definition of Fibonacci numbers: f(0) = 0 f(1) = 1 f(n) = f(n-1) + f(n-2) for n ≥ 2 • Computing the nth Fibonacci number recursively (topdown): f(n) f(n-1) f(n-2) + + f(n-3) f(n-2) f(n-3) + f(n-4) 10
  • 11. Fib vs. fibDyn int fib(int n) { if (n <= 1) return n; // stopping conditions else return fib(n-1) + fib(n-2); // recursive step } int fibDyn(int n, vector<int>& fibList) { int fibValue; if (fibList[n] >= 0) // check for a previously computed result and return return fibList[n]; // otherwise execute the recursive algorithm to obtain the result if (n <= 1) // stopping conditions fibValue = n; else // recursive step fibValue = fibDyn(n-1, fibList) + fibDyn(n-2, fibList); // store the result and return its value fibList[n] = fibValue; return fibValue; } 11
  • 12. Example: Fibonacci numbers Computing the nth fibonacci number using bottom-up iteration: • f(0) = 0 • f(1) = 1 • f(2) = 0+1 = 1 • f(3) = 1+1 = 2 • f(4) = 1+2 = 3 • f(5) = 2+3 = 5 • • • • f(n-2) = f(n-3)+f(n-4) • f(n-1) = f(n-2)+f(n-3) • f(n) = f(n-1) + f(n-2) 12
  • 13. Recursive calls for fib(5) f ib ( 5 ) f ib ( 3 ) f ib ( 4 ) f ib ( 3 ) f ib ( 2 ) f ib ( 1 ) f ib ( 2 ) f ib ( 1 ) f ib ( 1 ) f ib ( 1 ) f ib ( 2 ) f ib ( 0 ) f ib ( 1 ) f ib ( 0 ) f ib ( 0 ) 13
  • 14. fib(5) Using Dynamic Programming f ib ( 5 ) 6 f ib ( 4 ) f ib ( 3 ) 5 f ib ( 3 ) f ib ( 2 ) f ib ( 1 ) f ib ( 2 ) 4 f ib ( 2 ) f ib ( 1 ) f ib ( 1 ) f ib ( 0 ) f ib ( 1 ) f ib ( 0 ) 3 f ib ( 1 ) f ib ( 0 ) 1 2 14
  • 15. Statistics (function calls) fib fibDyn N = 20 21,891 39 N = 40 331,160,281 79 15
  • 16. Top down vs. Bottom up  Top down dynamic programming moves through recursive process and stores results as algorithm computes  Bottom up dynamic programming evaluates by computing all function values in order, starting at lowest and using previously computed values. 16
  • 17. Examples of Dynamic Programming Algorithms • Computing binomial coefficients • Optimal chain matrix multiplication • Floyd’s algorithms for all-pairs shortest paths • Constructing an optimal binary search tree • Some instances of difficult discrete optimization problems: • travelling salesman • knapsack 17
  • 18. A framework to solve Optimization problems  For – – – each current choice: Determine what subproblem(s) would remain if this choice were made. Recursively find the optimal costs of those subproblems. Combine those costs with the cost of the current choice itself to obtain an overall cost for this choice  Select a current choice that produced the minimum overall cost. 18
  • 19. Elements of Dynamic Programming  Constructing solution to a problem by building it up dynamically from solutions to smaller (or simpler) subproblems – – sub-instances are combined to obtain sub-instances of increasing size, until finally arriving at the solution of the original instance. make a choice at each step, but the choice may depend on the solutions to sub-problems. 19
  • 20. Elements of Dynamic Programming …  Principle of optimality –  the optimal solution to any nontrivial instance of a problem is a combination of optimal solutions to some of its sub-instances. Memorization (for overlapping sub-problems) – – avoid calculating the same thing twice, usually by keeping a table of know results that fills up as subinstances are solved. 20
  • 21. Development of a dynamic programming algorithm     Characterize the structure of an optimal solution – Breaking a problem into sub-problem – whether principle of optimality apply Recursively define the value of an optimal solution – define the value of an optimal solution based on value of solutions to sub-problems Compute the value of an optimal solution in a bottom-up fashion – compute in a bottom-up fashion and save the values along the way – later steps use the save values of pervious steps Construct an optimal solution from computed information 21
  • 22. Binomial Coefficient  Binomial coefficient: n  n!  = k  k!( n −k )!     for 0 ≤ k ≤ n Cannot compute using this formula because of n! Instead, use the following formula: 22
  • 23. Binomial Using Divide & Conquer  Binomial formula:   n − 1   n − 1 C  k − 1 + C  k  0 < k < n     n      C  =  k  n  n    1 k = 0 or k = n (C   or C   )  0  n       23
  • 24. Binomial using Dynamic Programming   Just like Fibonacci, that formula is very inefficient Instead, we can use the following: (a + b) n = C (n,0)a n + ... + C (n, i )a n −i b i + ... + C (n, n)b n 24
  • 25. Bottom-Up  Recursive – B[i] [j] = property: B[i – 1] [j – 1] + B[i – 1][j] 0 < j < i 1 j = 0 or j = i 25
  • 26. Pascal’s Triangle 0 1 0 1 1 1 1 2 1 2 1 3 1 3 3 1 4 1 4 6 4 … i n 2 3 4 … j k 1 B[i-1][j-1]+ B[i-1][j] B[i][j] 26
  • 27. Binomial Coefficient  Record the values in a table of n+1 rows and k+1 columns 0 1 2 0 1 1 2 1 3 3 k 1 3 k-1 1 2 … 1 1 3 1 ... k 1 1 … n-1 1 n 1  n − 1 C  k − 1     n − 1 C k     n  C  k    27
  • 28. Binomial Coefficient ALGORITHM Binomial(n,k) //Computes C(n, k) by the dynamic programming algorithm //Input: A pair of nonnegative integers n ≥ k ≥ 0 //Output: The value of C(n ,k) for i 0 to n do for j 0 to min (i ,k) do if j = 0 or j = k C [i , j]  1 else C [i , j]  C[i-1, j-1] + C[i-1, j] return C [n, k] k i −1 A( n, k ) = ∑∑1 + i =1 j =1 = n k k n i =1 i =K +1 ∑ ∑1 = ∑(i −1) + ∑k i =k +1 j =1 ( k −1) k + k ( n − k ) ∈Θ( nk ) 2 28
  • 29. Floyd’s Algorithm: All pairs shortest paths •Find shortest path when direct path doesn’t exist •In a weighted graph, find shortest paths between every pair of vertices • Same idea: construct solution through series of matrices D(0), D(1), … using an initial subset of the vertices as 4 3 intermediaries. 1 • Example: 1 6 1 5 2 3 4 29
  • 30. Shortest Path    Optimization problem – more than one candidate for the solution Solution is the candidate with optimal value Solution 1 – brute force – –  Find all possible paths, compute minimum Efficiency? Worse than O(n2) Solution 2 – dynamic programming – – Algorithm that determines only lengths of shortest paths Modify to produce shortest paths as well 30
  • 32. Meanings       D(0)[2][5] = lenth[v2, v5]= ∞ D(1)[2][5] = minimum(length[v2,v5], length[v2,v1,v5]) = minimum (∞, 14) = 14 D(2)[2][5] = D(1)[2][5] = 14 D(3)[2][5] = D(2)[2][5] = 14 D(4)[2][5] = minimum(length[v2,v1,v5], length[v2,v4,v5]), length[v2,v1,v5], length[v2, v3,v4,v5]), = minimum (14, 5, 13, 10) = 5 D(5)[2][5] = D(4)[2][5] = 5 32
  • 33. Floyd’s Algorithm 2 a 7 6 3 b c d 1 ( ( ( ( ( d ijk ) = min{d ijk −1) , d ikk −1) + d kjk −1) } for k ≥ 1, d ij0 ) = wij 33
  • 34. Computing D  D(0) =W  Now compute D(1)  Then D(2)  Etc. 34
  • 35. Floyd’s Algorithm: All pairs shortest paths • ALGORITHM Floyd (W[1 … n, 1… n]) •For k ← 1 to n do •For i ← 1 to n do •For j ← 1 to n do •W[i, j] ← min{W[i,j], W{i, k] + W[k, j]} •Return W •Efficiency = ? Θ(n) 35
  • 36. Example: All-pairs shortest-path problem Example: Apply Floyd’s algorithm to find the t Allpairs shortest-path problem of the digraph defined by the following weight matrix 0 6 ∞ ∞ 3 2 0 ∞ ∞ ∞ ∞ 3 0 2 ∞ 1 2 4 0 ∞ 8 ∞ ∞ 3 0 36
  • 38. Chained Matrix Multiplication  Problem: Matrix-chain multiplication – a chain of <A1, A2, …, An> of n matrices –    find a way that minimizes the number of scalar multiplications to compute the product A1A2…An Strategy: Breaking a problem into sub-problem – A1A2...Ak, Ak+1Ak+2…An Recursively define the value of an optimal solution – m[i,j] = 0 if i = j – m[i,j]= min{i<=k<j} (m[i,k]+m[k+1,j]+pi-1pkpj) – for 1 <= i <= j <= n 38
  • 39. Example  Suppose we want to multiply a 2x2 matrix with a 3x4 matrix  Result is a 2x4 matrix  In general, an i x j matrix times a j x k matrix requires i x j x k elementary multiplications 39
  • 40. Example  Consider multiplication of four matrices: A (20 x 2)  x B (2 x 30) x C (30 x 12) x D (12 x 8) Matrix multiplication is associative A(B (CD)) = (AB) (CD)  Five different orders for multiplying 4 matrices 1. 2. 3. 4. 5. A(B (CD)) = 30*12*8 + 2*30*8 + 20*2*3 = 3,680 (AB) (CD) = 20*2*30 + 30*12*8 + 20*30*8 = 8,880 A ((BC) D) = 2*30*12 + 2*12*3 + 20*2*8 = 1,232 ((AB) C) D = 20*2*30 + 20*30*12 + 20*12*8 = 10,320 (A (BC)) D = 2*30*12 + 20*2*12 + 20*12*8 = 3,120 40
  • 41. Algorithm int minmult (int n, const ind d[], index P[ ] [ ]) { index i, j, k, diagonal; int M[1..n][1..n]; for (i = 1; i <= n; i++) M[i][i] = 0; for (diagonal = 1; diagonal <= n-1; diagonal++) for (i = 1; i <= n-diagonal; i++) { j = i + diagonal; M[i] [j] = minimum(M[i][k] + M[k+1][j] + d[i-1]*d[k]*d[j]); // minimun (i <= k <= j-1) P[i] [j] = a value of k that gave the minimum; } return M[1][n]; } 41
  • 42. Optimal Binary Trees  Optimal way of constructing a binary search tree  Minimum depth, balanced (if all keys have same probability of being the search key)  What if probability is not all the same?  Multiply probability of accessing that key by number of links to get to that key 42
  • 43. Example If p1 = 0.7 Key3 p2 = 0.2 3(0.7) + 2(0.2) + 1(0.1) = 2.6 p3 = 0.1 key2 Θ (n3) Efficiency key1 43
  • 44. Traveling Salesperson  The Traveling Salesman Problem (TSP) is a deceptively simple combinatorial problem. It can be stated very simply:  A salesman spends his time visiting n cities (or nodes) cyclically. In one tour he visits each city just once, and finishes up where he started. In what order should he visit them to minimize the distance traveled? 44
  • 45. Why study?    The problem has some direct importance, since quite a lot of practical applications can be put in this form. It also has a theoretical importance in complexity theory, since the TSP is one of the class of "NP Complete" combinatorial problems. NP Complete problems are intractable in the sense that no one has found any really efficient way of solving them for large n. – They are also known to be more or less equivalent to each other; if you knew how to solve one kind of NP Complete problem you could solve the lot. 45
  • 46. Efficiency  The holy grail is to find a solution algorithm that gives an optimal solution in a time that has a polynomial variation with the size n of the problem.  The best that people have been able to do, however, is to solve it in a time that varies exponentially with n. 46
  • 47. Later…  We’ll get back to the traveling salesperson problem in the next chapter…. 47
  • 49. Chapter Summary • Dynamic programming is similar to divide-andconquer. • Dynamic programming is a bottom-up approach. • Dynamic programming stores the results (small instances) in the table and reuses it instead of recomputing it. • Two steps in development of a dynamic programming algorithm: • Establish a recursive property • Solve an instance of the problem in a bottom-up 49
  • 51. Rules of Sudoku • Place a number (1-9) in each blank cell. • Each row (nine lines from left to right), column (also nine lines from top to bottom) and 3x3 block bounded by bold line (nine blocks) contains number from 1 through 9. 51

Editor's Notes

  1. {}