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[i][j]表示s1的i位和s2的j位是否交织。
特别注意交织时候有重复解的情况,如果s3[k]与s1[i]相等,那么Dp 寻找Dp[i-1][j]。
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int m = s1.length();
int n = s2.length();
if(m+n!=s3.length())
return false;
vector<vector<bool>> Dp(m+1,vector<bool>(n+1,false));
Dp[0][0] = true;
for(int i=0; i<m; ++i){
if(s1[i]==s3[i])
Dp[i+1][0] = Dp[i][0];
}
for(int j=0; j<n; ++j){
if(s2[j]==s3[j])
Dp[0][j+1] = Dp[0][j];
} //动态规划初始解
for(int i=1; i<=m; ++i){
for(int j=1; j<=n; ++j){
int k = i+j;
if(s3[k-1]==s2[j-1]){
Dp[i][j] = Dp[i][j]||Dp[i][j-1];
}
if(s3[k-1]==s1[i-1]){
Dp[i][j] = Dp[i-1][j]||Dp[i][j];
}//避免重复解
}
}
return Dp[m][n];
}
};