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.
Recurse: Judge Small: Accepted! Judge Large: Time Limit Exceeded
bool isInterleave(string s1, string s2, string s3) { if (s1.length() == 0) return s3 == s2; if (s2.length() == 0) return s3 == s1; if (s3.length() == 0) return s1.length() + s2.length() == 0; if (s1[0] == s3[0] && s2[0] != s3[0]) return isInterleave(s1.substr(1), s2, s3.substr(1)); else if (s1[0] != s3[0] && s2[0] == s3[0]) return isInterleave(s1, s2.substr(1), s3.substr(1)); else if (s1[0] == s3[0] && s1[0] == s3[0]) return isInterleave(s1.substr(1), s2, s3.substr(1)) || isInterleave(s1, s2.substr(1), s3.substr(1)); else return false ; }
2-dimension dp:
这是一个二维的动态规划,
s1 = "aabcc" s2 = "dbbca" s3 = "aadbbcbcac"
class Solution { public : bool dp[101][101]; bool isInterleave(string s1, string s2, string s3) { int size1 = s1.length(); int size2 = s2.length(); int size3 = s3.length(); if ( size1 + size2 != size3) return false ; memset(dp, false , sizeof ( bool )*101*101); dp[0][0] = true ; for ( int i = 1; i <= size1; ++i) if (s1[i-1] == s3[i-1]) dp[i][0] = true ; else break ; for ( int j = 1; j <= size2; ++j) if (s2[j-1] == s3[j-1]) dp[0][j] = true ; else break ; int k; for ( int i = 1; i <= size1; ++i) for ( int j = 1; j <= size2; ++j) { k = i + j; if (s1[i-1] == s3[k-1]) dp[i][j] = dp[i-1][j] || dp[i][j]; if (s2[j-1] == s3[k-1]) dp[i][j] = dp[i][j-1] || dp[i][j]; } return dp[size1][size2]; } };