leetcode
72. Edit Distance
space = O(mn)解法
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length();
vector<vector<int>> result(m+1, vector<int> (n+1, 0));
for(int i = 0; i != m + 1; ++i)
result[i][0] = i;
for(int j = 0; j != n + 1; ++j)
result[0][j] = j;
for(int i = 1; i != m + 1; ++i)
for(int j = 1; j != n + 1; ++j) {
if(word1[i - 1] == word2[j - 1])
result[i][j] = result[i - 1][j - 1];
else
result[i][j] = min(result[i - 1][j], min(result[i][j - 1], result[i - 1][j - 1])) + 1;
}
return result[m][n];
}
};
space o(n)的解法,用一个m+1容器保存结果,每一个结果result[i]只跟result[i - 1][j] result[i - 1][j - 1] result[i][j - 1]有关
一直在纠结三个需要保存的变量 result[i - 1][j - 1], result[i][j - 1] , result[i - 1][ j ].
temp用来保存result[i - 1][j]
result[i][j - 1]每次循环不变 result[i - 1][ j -1]用pre保存
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length();
vector<int> result(m + 1, 0);//word1 length = m 不变
for(int i = 1; i != m + 1; ++i)
result[i] = i; // default:word2 length = 0;
for(int j = 1; j != n + 1; ++j) {//word2 length = n 从1逐个加过去
int pre = result[0];
result[0] = j;
for(int i = 1; i != m + 1; ++i){
int temp = result[i];
if(word1[i - 1] == word2[j - 1])
result[i] = pre;
else
result[i] = min(pre, min(result[i - 1], result[i])) + 1;
pre = temp;
}
}
return result[m];
}
};