Lecture 18 - 19 - Dynamic Programming
Lecture 18 - 19 - Dynamic Programming
Dynamic Programming
Introduction to Algorithms
Da Nang University of Science and Technology
((A1A2)(A3((A4A5)A6))) ((A7A8)A9)
Contradiction!
Intelligent Networking Laboratory DANG THIEN BINH 11/32
Step 2
A Recursive Solution
Subproblem
Determine the minimum cost of a parenthesization of
𝐴𝑖 𝐴𝑖+1 … 𝐴𝑗 (1 ≤ 𝑖 ≤ 𝑗 ≤ 𝑛)
𝑚[𝑖, 𝑗]: the minimum number of scalar multiplications
needed to compute the matrix 𝐴𝑖..𝑗
𝑚[𝑖, 𝑗] = 𝑚[𝑖, 𝑘] + 𝑚[𝑘 + 1, 𝑗] + 𝑝𝑖−1 𝑝𝑘 𝑝𝑗
However, we do not know the value of 𝑘 (𝑠[𝑖, 𝑗]),
so we have to try all j-i possibilities
0 if i = j
m[i, j ] = {m[i, k ] + m[k + 1, j ]} + pi −1 pk p j if i j
min
ik j
A recursive solution takes exponential time
l =3
l=2
35x15x5=2625 10x20x25=5000
(( 𝐴1 ( 𝐴2 𝐴3 ) ) ( ( 𝐴4 𝐴5 ) 𝐴6 ))
𝑇(𝑛) ≥ 2 𝑇(𝑖) + 𝑛
𝑖=1
𝑇(𝑛) ≥ 2 2𝑖−1 + 𝑛 = 2 2𝑖 + 𝑛
𝑖=1 𝑖=0
= 2(2𝑛−1 − 1) + 𝑛 = (2𝑛 − 2) + 𝑛 ≥ 2𝑛−1
LCS-LENGTH(X, Y) is (𝒎𝒏)
PRINT-LCS(b, X, i, j) is 𝑶(𝒎 + 𝒏)