https://leetcode.com/problems/edit-distance/description/
DP
class Solution { public: int minDistance(string word1, string word2) { int m = word1.length(), n = word2.length(); vector<vector<int>> dp(m+1, vector<int>(n+1, INT_MAX)); 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 dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1; } return dp[m][n]; } };
递归 (bad performance, should change cache key to index [i,j] in the two words)
class Solution { public: map<pair<string,string>, int> cache; int minDistance(string word1, string word2) { auto key = make_pair(word1, word2); if (cache.count(key)) return cache[key]; if (word1 == word2) return 0; int idx = 0; while (word1[idx] == word2[idx]) idx++; if (idx == word1.length()) return word2.length() - idx; if (idx == word2.length()) return word1.length() - idx; int res = 1 + min( minDistance(word1.substr(idx+1),word2.substr(idx+1)), // replace current min( minDistance(word1.substr(idx+1),word2.substr(idx)), // delete one from first minDistance(word1.substr(idx),word2.substr(idx+1)) // delete one from second )); cache[key] = res; return res; } };