題目:
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.
分析:
假如函數bool isInterleaving(string &s1, int len1, string &s2, int len2, string &s3, int len3);
表示子問題:si取前leni個字符的話,那麼實際上可以得到這樣的一個公式:
isInterleaving(s1,len1,s2,len2,s3,len3)
= (s3.lastChar == s1.lastChar) && isInterleaving(s1,len1 - 1,s2,len2,s3,len3 - 1)
||(s3.lastChar == s2.lastChar) && isInterleaving(s1,len1,s2,len2 - 1,s3,len3 - 1)由於len3 === len1 + len2,所以這個問題裡面實際上存在著兩個變量,是一個二維動態規劃題目。
從矩陣的角度來看的話,每一個元素的值,依賴於它的上邊和左邊兩個值。
代碼如下:
bool isInterleave(string s1, string s2, string s3) {
if(s1.size() + s2.size() != s3.size())return false;
bool **f=new bool*[s1.size()+1];
for(int i=0;i<=s1.size();i++)
{
f[i]=new bool[s2.size()+1];
}
f[0][0]=true;
for(int i = 1; i <= s1.size(); i++)
{
f[i][0]=f[i-1][0] && (s3[i-1] == s1[i-1]);
}
for(int i = 1; i <= s2.size(); i++)
{
f[0][i]=f[0][i-1] && (s3[i-1] == s2[i-1]);
}
for(int i = 1; i <= s1.size(); i++)
{
for(int j = 1; j <= s2.size(); j++)
{
f[i][j]=(f[i-1][j]&&s1[i-1]==s3[i+j-1])||(f[i][j-1]&&s2[j-1]==s3[i+j-1]);
}
}
return f[s1.size()][s2.size()];
}