https://leetcode.com/problems/edit-distance/
递归:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45class Solution {
public:
int minDistance(string word1, string word2) {
if(word1.size() == 0){
return word2.size();
}
if(word2.size() == 0){
return word1.size();
}
int m = word1.size();
int n = word2.size();
vector<vector<int> > arr(m, vector<int>(n, 0));
return dfs(word1, 0, word2, 0, arr);
}
int dfs(string & word1, int i, string & word2, int j, vector<vector<int> > & arr){
if(i == word1.size())
return word2.size() - j;
if(j == word2.size())
return word1.size() - i;
if(arr[i][j])
return arr[i][j];
int res = 0;
if(word1[i] == word2[j]){
return dfs(word1, i+1, word2, j+1, arr);
}
else{
int insert_cnt = dfs(word1, i, word2, j+1, arr);
int delete_cnt = dfs(word1, i+1, word2, j, arr);
int replace_cnt = dfs(word1, i+1, word2, j+1, arr);
res = min(insert_cnt, min(delete_cnt, replace_cnt)) + 1;
}
arr[i][j] = res;
return res;
}
};
动态规划1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35class Solution {
public:
int minDistance(string word1, string word2) {
if(word1.size() == 0){
return word2.size();
}
if(word2.size() == 0){
return word1.size();
}
int m = word1.size();
int 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] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
}
}
}
return dp[m][n];
}
};