Dynamic Programming - Longest Common Subsequence (LCS)
Dynamic Programming - Longest Common Subsequence (LCS)
• Dynamic programming;
• Dynamic programming;
fib(3) fib(2)
fib(1)
fib(2) fib(0)
fib(1)
fib(1) fib(0)
The classic application of dynamic programming to this
problem is to create a “look-up” table to store results
for later.
LookUp[i][j]= 1+ LookUp[i+1][j+1]
LookUp[i][j]=
maximum(LookUp[i+1][j] AND LookUp[i][j+1])
Let s1= “abde”, s2= “ada”, and consider its Rule 1 here,
corresponding LookUp table. since at least
one of the
substrings is
“abde” “bde” “de” “e” “”
empty.
“ada” 1+ 1 max(1, 1) max(1,0) max(0, 0) 0
Rule 2 here,
“da” max(1, 1) max(0, 1) 1+ 0 max(0, 0) 0 since
substrings
“a” 1+ 0 0 begin with
max(0, 0)max(0, 0) max(0, 0)
the same
letter.
“” 0 0 0 0 0
“ada” 2 1 1 0 0
“da” 1 1 1 0 0
“a” 1 0 0 0 0
“” 0 0 0 0 0
#include<string>
#include<vector>
class subsequence
{
public:
// Constructor
subsequence(string s, string ss); // Initialises the strings; and
// the LookUp table
int lcss( int i, int j ); // Computes the length of the longest common
// subsequence of s1.substr(i, L1-1) and
//s2.substr(j, L2-1), and all the LookUp entries.
private :
string s1;
string s2;
int L1; // Length of s1
int L2; // Length of s2
int LookUp[L1+1][L2+1];
};
A recursive solution.
else { int t1= lcss(i+1, j); // Apply Rule (3) ... but look up lcss(i+1, j)
int t2= lcss(i, j+1); // lookup lcss(i, j+1)...
if (t1 > t2) LookUp[i][j]= t1;
else LookUp[i][j]= t2;
}
}
}
return LookUp[i][j]; // In either case, just return the computed value of
// LookUp[i][j]
}
“ada” 2 1 1 0 0
“da” 1 1 1 0 0
“a” 1 0 0 0 0
“” 0 0 0 0 0
An iterative solution.
return LookUp[i][j];
}
Tree data types:
• Quadtrees.
Trees can be used to represent parent/child
relationships between data.
EITHER T is empty,
H(T)= 0, if T is empty;
H(T)= 1 + maximum(H(T_1), H(T_2)), where
T_1 and T_2 are the subtrees of T.
b c
d e f
Programming trees.
b c
d e f
Binary search trees, are a special type of binary tree
in which searching is easy, because the nodes are all
ordered relative to eachother. (Carrano, page
536--574)
(a) T’s root item is greater than all the node items of
its left subtree, and
(b) T’s root item is less than all the node items of its
right subtree, and
b g
a d h