Recursion (Brute Force)
Intuition
Compare characters from both strings starting at the end. If the characters match, they are part of the LCS and we recurse on both strings with one less character. If they do not match, we try two options: skip the last character of text1 or skip the last character of text2, and take the maximum. This explores all possible subsequence pairings but has exponential overlap.
Algorithm
- If either string is empty, return `0`.
- If the last characters match, return `1 + recurse(text1[:-1], text2[:-1])`.
- Otherwise, return `max(recurse(text1[:-1], text2), recurse(text1, text2[:-1]))`.
O(2^(m+n)) where m and n are the lengths of the two stringsSpaceO(m + n) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
return helper(text1, text2, text1.size() - 1, text2.size() - 1);
}
int helper(string& s1, string& s2, int i, int j) {
if (i < 0 || j < 0) return 0;
if (s1[i] == s2[j]) {
return 1 + helper(s1, s2, i - 1, j - 1);
}
return max(helper(s1, s2, i - 1, j), helper(s1, s2, i, j - 1));
}
};class Solution {
public int longestCommonSubsequence(String text1, String text2) {
return helper(text1, text2, text1.length() - 1, text2.length() - 1);
}
private int helper(String s1, String s2, int i, int j) {
if (i < 0 || j < 0) return 0;
if (s1.charAt(i) == s2.charAt(j)) {
return 1 + helper(s1, s2, i - 1, j - 1);
}
return Math.max(helper(s1, s2, i - 1, j), helper(s1, s2, i, j - 1));
}
}class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
def helper(i: int, j: int) -> int:
if i < 0 or j < 0:
return 0
if text1[i] == text2[j]:
return 1 + helper(i - 1, j - 1)
return max(helper(i - 1, j), helper(i, j - 1))
return helper(len(text1) - 1, len(text2) - 1)func longestCommonSubsequence(text1 string, text2 string) int {
var helper func(i, j int) int
helper = func(i, j int) int {
if i < 0 || j < 0 {
return 0
}
if text1[i] == text2[j] {
return 1 + helper(i-1, j-1)
}
a := helper(i-1, j)
b := helper(i, j-1)
if a > b {
return a
}
return b
}
return helper(len(text1)-1, len(text2)-1)
}