Problem
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We can use dynamic programming to solve this problem.
-
Dynamic state is a two dimensional boolean array
dp[i][j]
, which means the result of choosing s1’s character from beginning to thei
th character inclusive and s2’s character from beginning to thej
th character inclusive to check if they are interleaving with s3 of choosing from the beginning to thei+j
th character. -
Dynamic init is
dp[0][0] = true
because if s1 and s2 are empty, then they are interleaving of s3 with choosing zero length. -
Dynamic function: If s1’s length is the row and s2’s length is the column, and we want to find the result of
dp[i][j]
, then if s1’s last character which is thei
th character is the same as the s3’s last character which is thei+j
th character, then the result ofdp[i][j]
is the same asdp[i-1][j]
(top). Similarlly, if s2’s last character is the same as s3’s last character, then the result ofdp[i][j]
is the same asdp[i][j-1]
(left). -
Dynamic result is choosing all character of s1 and choosing all character of s2, so it’s in the bottom right, which is
dp[s1.length()][s2.length()]
.
Solution
1 |
|