题目:biubiu
题意:给两个单词word1和word2,可以对word1的某一个字符进行插入、删除、替换,问需要多少步可以将word1转成word2,
dfs递归暴力:
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
void dfs(string word1, string word2,int x,int y,int sum) {
if (x == word1.size() && y == word2.size()) {
ans = min(ans, sum);
return;
}
if (x == word1.size() ) {
sum += (word2.size() - y);
ans = min(ans, sum);
return;
}
if (y == word2.size()) {
sum += (word1.size() - x);
ans = min(ans, sum);
return;
}
if (word1[x] == word2[y]) {
dfs(word1, word2, x + 1, y + 1, sum);
return;
}
else {
for (int i = 1; i <= 3; i++) {
if (i == 1) { ///插入
dfs(word1, word2, x, y + 1, sum + 1);
}
else if (i == 2) { ///删除
dfs(word1, word2, x + 1, y , sum + 1);
}
else { ///替换
dfs(word1, word2, x + 1, y + 1, sum+1);
}
}
}
return;
}
int minDistance(string word1, string word2) {
ans = INT_MAX;
dfs(word1, word2, 0, 0, 0);
return this->ans;
}
private:
int ans;
};
int main() {
string word1, word2;
while (cin >> word1 >> word2) {
Solution s;
cout << s.minDistance(word1, word2) << endl;
}
return 0;
}
暴力不一定出奇迹,时间超限。
动态规划:
字符匹配的三种状态:
1:word1插入一个字符(word2删除一个字符)
2:word2插入一个字符(word1删除一个字符)
3:word1修改一个字符(word2修改一个字符)
所以 dp[i][j] 的来源就来自于三种状态 dp[i-1][j] 、dp[i][j-1]、dp[i-1][j-1]
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector<vector<int>>dp(m+1, vector<int>(n+1,INT_MAX));
dp[0][0] = 0;
for (int i = 1; i <= m; i++)
dp[i][0] = i;
for (int i = 1; i <= n; i++)
dp[0][i] = i;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1[i-1] == word2[j-1]) {
dp[i][j] = min(dp[i-1][j]+1, min(dp[i - 1][j - 1], dp[i][j - 1]+1));
}
else {
dp[i][j] = min(dp[i-1][j]+1,min (dp[i - 1][j - 1] + 1, dp[i][j - 1] + 1) );
}
}
}
return dp[m][n];
}
};
int main() {
string word1, word2;
while (cin >> word1 >> word2) {
Solution s;
cout << s.minDistance(word1, word2) << endl;
}
return 0;
}