1. Recursive Exhaustive Search
Intuition
Check characters from end to start: if equal, add 1 and recurse on both prefixes; else branch into dropping one character from text1 or text2.
Algorithm
- Define
dfs(i, j). - If
i == 0orj == 0, return 0. - If
text1[i-1] == text2[j-1], return1 + dfs(i-1, j-1). - Return
max(dfs(i-1, j), dfs(i, j-1)).
#include <iostream>#include <string>#include <algorithm> using namespace std; int dfs(int i, int j, const string& s1, const string& s2) { if (i == 0 || j == 0) return 0; if (s1[i - 1] == s2[j - 1]) { return 1 + dfs(i - 1, j - 1, s1, s2); } return max(dfs(i - 1, j, s1, s2), dfs(i, j - 1, s1, s2));} int lcsRec(string text1, string text2) { return dfs(text1.length(), text2.length(), text1, text2);} int main() { string t1 = "abcde", t2 = "ace"; cout << "LCS (Recursive): " << lcsRec(t1, t2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^(m + n)) - Space complexity:
O(m + n) call stack