1. Recursive Character Interleaving
Intuition
Recursively try choosing characters from str1 or str2 to construct the shortest valid supersequence.
Algorithm
- Define
solve(i, j). - If
i == m, return remaining ofstr2[j..]. - If
j == n, return remaining ofstr1[i..]. - If
str1[i] == str2[j], returnstr1[i] + solve(i + 1, j + 1). - Option 1:
str1[i] + solve(i + 1, j). - Option 2:
str2[j] + solve(i, j + 1). - Return the option with smaller string length.
#include <iostream>#include <string>#include <algorithm> using namespace std; class Solution { string solve(int i, int j, const string& s1, const string& s2) { if (i == s1.length()) return s2.substr(j); if (j == s2.length()) return s1.substr(i); if (s1[i] == s2[j]) { return s1[i] + solve(i + 1, j + 1, s1, s2); } string opt1 = s1[i] + solve(i + 1, j, s1, s2); string opt2 = s2[j] + solve(i, j + 1, s1, s2); return (opt1.length() <= opt2.length()) ? opt1 : opt2; }public: string shortestCommonSupersequence(string str1, string str2) { return solve(0, 0, str1, str2); }}; int main() { Solution sol; cout << "SCS: " << sol.shortestCommonSupersequence("abac", "cab") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^(m + n)) - Space complexity:
O(m + n)