I am trying to understand backtracking. For that I started with the following link - http://en.wikibooks.org/wiki/Algorithms/Backtracking
It has explained LCS. I understand dynamic programming solution will be faster, but I am taking one step at a time. Is the pseudo code they have provided, correct? For this : String[] a = {"The", "great", "square", "has", "a", "same", "no", "corners"}; String[] b = {"The", "great", "image", "has", "no", "a", "same", "form"};
it also prints "no".
This is my attempt, can someone please improve / correct it.
public ArrayList<String> getLongestCommonSubsequence(String[] a , String[] b, ArrayList<String> output)
{
if(a.length == 0 || b.length == 0)
return output;
if(a[0]==b[0])
{
output.add(a[0]);
getLongestCommonSubsequence(Arrays.copyOfRange(a, 1, a.length), Arrays.copyOfRange(b, 1, b.length), output);
}
else
{
ArrayList<String> discardA = getLongestCommonSubsequence(Arrays.copyOfRange(a, 1, a.length), b, new ArrayList<String>());
ArrayList<String> discardB = getLongestCommonSubsequence(a, Arrays.copyOfRange(b, 1, b.length), new ArrayList<String>());
if(discardA.size() > discardB.size())
output = discardA;
if(discardB.size() > discardA.size())
output = discardB;
}
return output;
}
Updated method with the suggestion from @David Eisenstat - Problem 1 - It still prints out "no" Problem 2 - It gives out redundant values still. I think that's a side effect of using backtracking.
public ArrayList<String> getLongestCommonSubsequence(String[] a , String[] b, ArrayList<String> output)
{
if(a.length == 0 || b.length == 0)
return output;
if(a[0].equals(b[0]))
{
output.add(a[0]);
getLongestCommonSubsequence(Arrays.copyOfRange(a, 1, a.length), Arrays.copyOfRange(b, 1, b.length), output);
}
else
{
ArrayList<String> discardA = getLongestCommonSubsequence(Arrays.copyOfRange(a, 1, a.length), b, output);
ArrayList<String> discardB = getLongestCommonSubsequence(a, Arrays.copyOfRange(b, 1, b.length), output);
if(discardA.size() > discardB.size())
output.addAll(discardA);
else if(discardB.size() > discardA.size())
output.addAll(discardB);
}
return output;
}