Timeline
Timeline
2025-12-16
init
Dynamic Programming
Problem:
Let denote (where ) and (where ) can interleave to form 。 represents 、 and both are empty strings.
- Considering only s1, i.e.,
s1[0..=i-1]whether it can interleave to forms3[0..i-1], obviously
- Similarly, considering only s2, we have:
- Considering both s1 and s2, we have:
1234567891011121314151617181920212223242526272829303132333435363738394041 | using std::string;using std::vector;class Solution { public: bool isInterleave(string s1, string s2, string s3) { int n1 = s1.length(), n2 = s2.length(), n3 = s3.length(); int i, j; bool from_s1, from_s2; if (n1 + n2 != n3) { return false; } vector<vector<bool> > dp(n1 + 1, vector<bool>(n2 + 1, false)); // dp[i][j] denotes that s1[0..=i-1] and s2[0..=j-1] can interleave to form s3[0..=i+j-1] // dp[0][0] represents the empty string dp[0][0] = true; for (i = 1; i <= n1; i++) { dp[i][0] = dp[i - 1][0] && (s3[i - 1] == s1[i - 1]); } for (j = 1; j <= n2; j++) { dp[0][j] = dp[0][j - 1] && (s3[j - 1] == s2[j - 1]); } for (i = 1; i <= n1; i++) { for (j = 1; j <= n2; j++) { from_s1 = dp[i - 1][j] && (s1[i - 1] == s3[i + j - 1]); from_s2 = dp[i][j - 1] && (s2[j - 1] == s3[i + j - 1]); dp[i][j] = from_s1 || from_s2; } } return dp[n1][n2]; }}; |
