1. Recursive Branching Search
Intuition
At each step, check if the current character of s3 can be taken from s1, s2, or both, and recurse.
Algorithm
- If
s1.length + s2.length != s3.length, return false. - Define
dfs(i, j, k). - If
k == s3.length, return true. - If
i < s1.lengthands1[i] == s3[k]: ifdfs(i + 1, j, k + 1)returns true, return true. - If
j < s2.lengthands2[j] == s3[k]: ifdfs(i, j + 1, k + 1)returns true, return true. - Return false.
#include <iostream>#include <string> using namespace std; bool dfs(int i, int j, int k, const string& s1, const string& s2, const string& s3) { if (k == (int)s3.length()) return true; if (i < (int)s1.length() && s1[i] == s3[k]) { if (dfs(i + 1, j, k + 1, s1, s2, s3)) return true; } if (j < (int)s2.length() && s2[j] == s3[k]) { if (dfs(i, j + 1, k + 1, s1, s2, s3)) return true; } return false;} bool isInterleaveRec(string s1, string s2, string s3) { if (s1.length() + s2.length() != s3.length()) return false; return dfs(0, 0, 0, s1, s2, s3);} int main() { string s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"; cout << "Is Interleave (Recursive): " << (isInterleaveRec(s1, s2, s3) ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^(|s1| + |s2|)) - Space complexity:
O(|s1| + |s2|) call stack