int lcs(char[] x, int i, char[] y, int j) { if (i == 0 || j == 0) return 0; if (x[i - 1] == y[j - 1]) return lcs(x, i - 1, y, j - 1) + 1; return Math.max(lcs(x, i, y, j - 1), lcs(x, i - 1, y, j)); } print(lcs(x, x.length, y, y.length);
Below is a partial recursion tree:
lcs("ABCD", "AFDX") / \ lcs("ABC", "AFDX") lcs("ABCD", "AFD") / \ / \ lcs("AB", "AFDX") lcs("AXY", "AFD") lcs("ABC", "AFD") lcs("ABCD", "AF")
In the worst case, the length of the LCS is 0, which means the absence of a common subsequence. In this case, all possible subsequences are checked and substitutions O(2^n) exist.
source share