#include <algorithm>
#include <climits>
#include <iostream>
#include <string>
using namespace std;
//回溯算法
int ans = INT_MAX;
void backTracking(string& S, const string& T, int i, int j, int path){
// i 表示当前 S 的索引,j 表示 T 的索引,path 表示修改次数
if(i == S.size()){//表示对S的修改全部结束
ans = min(ans, path);
return;
}
if(j == T.size()){//超出了只能删除
//只能删除末尾
ans = min(ans, (path + static_cast<int>(S.size() - i)) );
return;
}
/*
策略 当前位置不改变 修改
剪枝当前字母配对成功则不做任何修改
*/
if(S[i] == T[j]){
backTracking(S, T, i+1, j+1, path);
}else{
//修改
backTracking(S, T, i + 1, j + 1, path + 1);
}
return;
}
int solution(string S, string T) {
// PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
// write code here
ans = INT_MAX; // 重新初始化 ans,以防多次调用 solution 函数时出现问题
backTracking(S, T, 0, 0, 0);
return ans;
}
int main() {
cout << (solution("jnjsmjgcyplywiwmb", "eefgegffege") == 17) << endl;
cout << (solution("abcd", "efg") == 4) << endl;
cout << (solution("xyz", "xy") == 1) << endl;
cout << (solution("hello", "helloworld") == 0) << endl;
cout << (solution("same", "same") == 0) << endl;
return 0;
}
这个题目很简单,我理解的时候认为删除的操作会在任何的位置因此采用了回溯算法。实际上该问的删除操作只在结尾出产生反而使问题简单化。