leetcode-72-线性DP-编辑距离 发表于 2020-04-27 | 分类于 数据结构与算法 题目 解法12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273// 递归 + 备忘录class Solution {public: typedef tuple<int, int> key; struct key_hash : public unary_function<key, size_t >{ size_t operator()(const key &k) const{ return get<0>(k) * 100 + get<1>(k); } }; unordered_map<key, int, key_hash> help; int minDistance(string word1, string word2) { return dp(word1, word2, word1.size()-1, word2.size()-1); } int dp(string word1, string word2, int i, int j){ auto i_j = make_tuple(i, j); if(help.count(i_j) > 0) return help[i_j]; if(i == -1) return j+1; if(j == -1) return i+1; if(word1[i] == word2[j]){ help[i_j] = dp(word1, word2, i-1, j-1); }else{ // 替换, 删除, 插入 help[i_j] = m_min( dp(word1, word2, i-1, j-1) + 1, dp(word1, word2, i-1, j) + 1, dp(word1, word2, i, j-1) + 1 ); } return help[i_j]; } int m_min(int a, int b, int c){ return min(a, min(b, c)); }};// 动态规划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{ dp[i][j] = m_min( dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i-1][j-1] + 1 ); } } } return dp[m][n]; } int m_min(int a, int b, int c){ return min(a, min(b, c)); }};