Dynamic Programming
1 | class Solution { |
Remarks:
- TC: $O(m\times n)$, SC: $O(m \times n)$.
- DP idea: we record the minimum operations needed to convert the first $i$ characters in
word1
to the first $j$ characters inword2
asdp[i][j]
. - Transform relationship:
a. if the two chars match, then we don’t need any extra operation, i.e.
$$
dp[i][j] = dp[i-1][j-1]
$$
b. if they doesn’t match, we have 3 operations:
(i) Insert a char, we add an char toword2[j-1]
,
$$
dp[i][j] = dp[i][j-1] + 1
$$
(ii) Delete a char, we remove an char ofword1[i-1]
,
$$
dp[i][j] = dp[i-1][j] + 1
$$
(iii) Replace a char, we convertword1[i-1]
toword2[j-1]
$$
dp[i][j] = dp[i-1][j-1] + 1
$$
We choose the minimum of all these three. - Initialization: $dp[0][j] = j$ (we add
j
chars to convert a empty string to firstj
chars), $dp[i][0] = i$.