# leetcode #72 in cpp

Solution:

We use DP where dp[i][j] represents minimum steps from word1[0...i-1] to words2[0...j-1]

Code:

class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.length();
int len2 = word2.length();
vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));//dp[i][j]-->min step convert word1[0..i-1] to word2[0...j-1]
dp[0][0] = 0;
for(int i = 1; i < len2+1; i ++){
dp[0][i] = i;
}
for(int i = 1; i< len1 + 1; i ++){
dp[i][0] = i;
}

for(int i = 1; i < len1+1; i++){
for(int j = 1; j < len2 + 1; j ++){
if(word1[i-1] == word2[j-1]){
dp[i][j] = dp[i-1][j-1];
}else{
//delete word1[i-1] and make word1[0...i-2] to word2[0..j-1], or replace word1[i-1] with word2[j-1]
int mini = min(dp[i-1][j], dp[i-1][j-1]);
//make word1[0...i-1] to word2[0...j-2], insert word2[j-1] into word1
mini = min(mini, dp[i][j-1]);
dp[i][j] = mini + 1;
}
}
}
return dp[len1][len2];
}
};

#### LeetCode72——Edit Distance

2015-11-14 14:07:54

#### Leetcode 72. Edit Distance 编辑距离 解题报告

2016-05-15 23:56:36

#### LeetCode(72)Edit Distance

2013-12-23 13:27:56

#### leetCode 72.Edit Distance (编辑距离) 解题思路和方法

2015-07-17 16:58:01

#### LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

#### (Java)LeetCode-72. Edit Distance

2016-11-09 17:03:29

#### 剑指offer(动态规划-LeetCode72)

2016-08-11 10:14:36

#### Leetcode 中 ListNode 的 reverse以及 快慢指针取中点

2016-12-24 10:49:31

#### LeetCode 72 Edit Distance(Python详解及实现)

2017-08-05 16:17:05