1. 程式人生 > >LeetCode動態規劃

LeetCode動態規劃

題目連結

Given s1s2s3, 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.

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
int m = s1.length();
int n = s2.length();//動態規劃
         if(m+n != s3.size())
            return false;
vector<vector<bool>> boolvec(m + 1, vector<bool>(n + 1,false));
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 && j == 0)
boolvec[0][0] = true;
else if (i == 0)
boolvec[i][j] = boolvec[i][j - 1] & (s2[j - 1] == s3[j - 1]);
else if (j == 0)
boolvec[i][j] = boolvec[i - 1][j] & (s1[i - 1] == s3[i - 1]);
else
boolvec[i][j] = (boolvec[i - 1][j] & (s3[i + j - 1] == s1[i - 1])) || (boolvec[i][j - 1] & (s3[i + j - 1] == s2[j - 1]));
}
}
return boolvec[m][n];
}
};