Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
Solution: 1. dp. O(MN) time & space. 'dp[i][j] == true' means that there is at least one way to construct
the string s3[0...i+j-1] by interleaving s1[0...j-1] and s2[0...i-1].
2. Recursion. Okay for Small but TLE for Large Test data.
1 class Solution { 2 public: 3 bool isInterleave(string s1, string s2, string s3) { 4 int M = s1.size(), N = s2.size(), K = s3.size(); 5 if (M + N != K) return false; 6 7 int dp[N+1][M+1]; 8 for (int i = 1; i <= N; ++i) 9 dp[i][0] = s2[i-1] == s3[i-1]; 10 for (int j = 1; j <= M; ++j) 11 dp[0][j] = s1[j-1] == s3[j-1]; 12 13 for (int i = 1; i <= N; ++i) 14 for (int j = 1; j <= M; ++j) 15 dp[i][j] = dp[i-1][j] && s2[i-1] == s3[i+j-1] || 16 dp[i][j-1] && s1[j-1] == s3[i+j-1]; 17 18 return dp[N][M]; 19 } 20 };