I've been trying to solve the LCS problem using recursion like below:
#include <iostream>
#include <string>
using namespace std;
string max(string x, string y) {
return x.size() <= y.size() ? y : x;
}
string find(string x, string y) {
// Find longest Sub Sequence
int firstSize = x.size();
int secondSize = y.size();
if (firstSize == 0 || secondSize == 0) {
return "";
}
if (x[firstSize - 1] == y[secondSize - 1]) {
char temp = x[firstSize - 1];
return find(x.erase(firstSize-1), y.erase(secondSize-1)) + temp;
}
return max(find(x, y.erase(secondSize - 1)), find(x.erase(firstSize - 1), y));
}
int main()
{
string x = "ABCBDAB";
string y = "BDCABA";
string result = find(x, y);
cout << "result = "<<result<< endl;
return 0;
}
The algorithm looks exactly, but the output is ABA subsequent that is wrong result, so something go wrong. The result is expected be a subsequent has length of 4 and I don't know exactly where I went wrong with the code. Why is it that ?