72. Edit distance (hard)
Code:
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.size(),m = word2.size();
vector<vector<int>>dp(n + 1,vector<int>(m + 1,0)); //dp数组,记录了word1到i位置,word2到j位置的最小步数
//dp数组边界的值?
for(int i = 0; i < n; ++i){
dp[i][0] = i;
}
for(int j = 0; j < m; ++j){
dp[0][j] = j;
}
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
if(word1[i] == word2[j]){
dp[i][j] = dp[i - 1][j - 1];
}
else{
dp[i][j] = min(dp[i - 1][j] + 1,dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1);
}
}
}
return dp[n][m];
}
};
You can see here that the error location is the min function.
wrong reason:
The min function in C++ only receives two variables for comparison. If three variables are compared, an error will occur.
In addition, the if comparison above is also wrong! word1 and word2 will cross the boundary!
correct code
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.size(),m = word2.size();
vector<vector<int>>dp(n + 1,vector<int>(m + 1,0)); //dp数组,记录了word1到i位置,word2到j位置的最小步数
//dp数组边界的值?
for(int i = 0; i <= n; ++i){
dp[i][0] = i;
}
for(int j = 0; j <= m; ++j){
dp[0][j] = j;
}
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++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] + 1, dp[i - 1][j - 1] + 1));
}
}
}
return dp[n][m];
}
};
Summarize
Setting up the initial conditions is a bit inelegant. Can be integrated into the overall for loop. Then the if statement in the for loop can be integrated into a ternary operator, so that one less if-else branch can be written. as follows
int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else {
dp[i][j] = min(
dp[i-1][j-1] + ((word1[i-1] == word2[j-1])? 0: 1),
min(dp[i-1][j] + 1, dp[i][j-1] + 1));
}
}
}
return dp[m][n];
}