# [72\. Edit Distance](https://leetcode.com/problems/edit-distance/) - 2 維 DP 矩陣,注意大小是 $(m + 1) \cdot (n + 1)$。 - 不需要編輯的狀況:`dp[i][j] = dp[i - 1][j - 1]` - 狀態轉移:`dp[i][j] = 1 + min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]})` :::spoiler Solution ```cpp= class Solution { public: int minDistance(string word1, string word2) { int m = word1.size(), n = word2.size(); vector<vector<int>> dp(m + 1, vector<int>(n + 1)); for (int i = 0; i <= m; ++i) dp[i][0] = i; for (int j = 0; j <= n; ++j) dp[0][j] = j; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (word1[i - 1] == word2[j - 1]) { // 不需要編輯的狀況 dp[i][j] = dp[i - 1][j - 1]; } else { // 新增 / 刪除 / 取代 三種情況 // + 1 代表做一次的操作 dp[i][j] = 1 + min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}); } } } return dp[m][n]; } }; ``` - 時間複雜度:$O(M \cdot N)$ - 空間複雜度:$O(M \cdot N)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up