我正在尝试编写一个递归算法来查找两个列表的最长公共子序列,如http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#LCS_function_defined中所述
似乎递归永远不会结束,我无法弄清楚我在做什么错
public static List<ActionType> getLongestSequence(List<ActionType> list1, List<ActionType> list2) {
return getLongestSequence(list1, list2, list1.size(), list2.size());
}
public static List<ActionType> getLongestSequence(List<ActionType> list1, List<ActionType> list2, int list1index, int list2index) {
if (list1index == 0 || list2index == 0) {
return new ArrayList<ActionType>();
}
if (list1.get(list1index-1).equals(list2.get(list2index-1))) {
List<ActionType> retVal = getLongestSequence(list1, list2, list1index-1, list2index-1);
retVal.add(list1.get(list1index-1));
return retVal;
} else {
List<ActionType> ret1 = getLongestSequence(list1, list2, list1index, list2index-1);
List<ActionType> ret2 = getLongestSequence(list1, list2, list1index-1, list2index);
if (ret1.size() > ret2.size()) {
return ret1;
} else {
return ret2;
}
}
}
任何解决此问题的帮助表示赞赏。谢谢你。