Dynamic Programming Example
Longest common subsequence
This is a typical recursive problem. The pseudocode is:
If S1[i] == S2[j], lcs(S1[i:],S2[j:]) = 1 + lcs(S1[i+1:],S2[j+1:])
else lcs(S1[i:],S2[j:]) = max(lcs(S1[i:],S2[j+1:]), lcs(S1[i+1s:],S2[j:]))
Recursive solution:
int longestCommonSubsequence(string text1, string text2) {
if(text1.size() == 0 || text2.size() == 0 ){
return 0;
}
if(text1[0] == text2[0]){
return 1 + longestCommonSubsequence(text1.substr(1, text1.size()-1), text2.substr(1, text1.size()-1));
}
return max(longestCommonSubsequence(text1, text2.substr(1, text1.size()-1)),
longestCommonSubsequence(text1.substr(1, text1.size()-1), text2));
}
Time complexity: O(2^n) Using dp could store the state that already calculate before.