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.
比较简单的二维DP,状态方程见代码。
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s1.length()+s2.length()!=s3.length()) return false; //剪枝
vector<vector<bool> > answer (s1.length()+1,(vector<bool>)(s2.length()+1));
if(s1.length()==0&&s2.length()==0) return (s3.length()==0);
if(s1.length()==0) return (s2==s3);
if(s2.length()==0) return (s1==s3);
answer[0][0] = true;
for(int i=1;i<=s1.length();i++)
{
answer[i][0] = (s1[i-1]==s3[i-1])&&answer[i-1][0];
}
for(int i=1;i<=s2.length();i++)
{
answer[0][i] = (s2[i-1]==s3[i-1])&&answer[0][i-1];
}
for(int i=1;i<=s1.length();i++)
{
for(int j=1;j<=s2.length();j++)
{
if(s1[i-1]==s2[j-1]&&s2[j-1]==s3[i+j-1])
{
answer[i][j] = answer[i-1][j]||answer[i][j-1];
}
else if(s1[i-1]==s3[i+j-1])
{
answer[i][j] = answer[i-1][j];
}
else if(s2[j-1]==s3[i+j-1])
{
answer[i][j] = answer[i][j-1];
}
else
{
answer[i][j] = false;
}
}
}
return answer[s1.length()][s2.length()];
}
};