Lecture 7 Dynamic Programming
Lecture 7 Dynamic Programming
Computer Algorithm
Lecture 7 Dynamic
Programming
Dynamic Programming
⚫ Matrix-Chain Multiplication
⚫ Longest Common Subsequence
⚫ Optimal Binary Search Tree
⚫ Greedy Method
– only one decision sequence is ever genertated.
⚫ Dynamic Programming
– Many decision sequences may be genertated.
⚫ Divide-and-Conquer
– partition the problem into independent
subproblems, solve the subproblems recursively,
and then combine their solutions to solve the
original problem
⚫ Dynamic Programming
– applicable when the subproblems are not
independent, that is, when subproblems share
subsubproblems.
C(n-1,k-1) + C(n-1,k) if o<k<n
C(n,k) = 1 if k =0 or k = n
0 otherwise
C(n,k)
{
if k = 0 or k =n then return 1
if k < 0 or k >n then return 0
return( C(n-1,k-1) + C(n-1,k) )
}
C(n-1,k-1) + C(n-1,k) if o<k<n
C(n,k) = 1 if k =0 or k = n
0 0 1 2 3
otherwise
0
1
2
C(6,3)
3
4
5
6
C(6,3) Repeat
C(5,2) C(5,3)
C(3,0) C(3,1)
C(2,0) C(2,1)
C(1,0) C(1,1)
C(n-1,k-1) + C(n-1,k) if o<k<n
C(n,k) = 1 if k =0 or k = n
0 0 1 2 3
otherwise
0
1 1 1
2 1 2 1
C(6,3) 1 3 3 1
3
4 4 6 4
5 10 10
6 20
C(6,3)
C(5,2) C(5,3)
C(3,0) C(3,1)
C(2,0) C(2,1)
No need to recalculate
C(1,0) C(1,1)
Memory every value
Lookup_C( n, k )
{
if k = 0 or k = n then return 1
if k < 0 or k > n then return 0
if c[n,k] < 0 then
c[n,k] = Lookup_C(n-1,k-1) + Lookup_C(n-1,k) )
return c[n,k]
}
C(n-1,k-1) + C(n-1,k) if o<k<n
C(n,k) = 1 if k =0 or k = n
0 0 1 2 3
otherwise
0 1
1 1 1
2 1 2 1
C(6,3) 1 3 3 1
3
4 1 4 6 4
5 1 5 10 10
6 1 6 15 20
7 8
C(3,1) C(3,2)
4 5 6
C(2,0) C(2,1) C(2,2)
2 3
C(1,0) C(1,1)
1
C(0,0)
⚫ X = < s, o, m, c, h, a, i >
subsequences of X
– < s, o, m, c, h, a, i > → < s, o, m >
– < s, o, m, c, h, a, i > → <c, h, a, i>
– < s, o, m, c, h, a, i > → <s, o, h, a, i>