This is classical matching DP. We can directly use the longest common subsequence solution's idea to solve this question.
The question asks us to delete some characters to make two strings the same. Actually, it is the same as finding the longest common subsequence. The only different thing is we need to consider the cost.
The DP array represents the mini cost to make two strings the same. It is a 2d array.
DP[i][j] = the min-cost to make the first i elements in s1 and the first j elements in s2 the same.
The only edge case we need to consider is when s2 is empty and s1 is not empty, we need to delete all the elements of s1, it would be a prefix sum, to s1 vice-versa.
the dp equation would be like, dp[i][j] = (s[i] == s[j]) ? dp[i - 1][j - 1] : min(dp[i - 1][j] + cost i, dp[i][j - 1] + cost j)
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
//dp[i][j] -> s1 i and s2 j makes them equal cost how much?
//dp[i][j] -> min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + s1==s2
//edge case dp[0][0]
//first mistake, forgot initilize the base case
int n1 = s1.length();
int n2 = s2.length();
vector<vector<int>> dp(n1 +1, vector<int>(n2 + 1, 0));
//base case
for(int i = 1; i <= n1; i++){
dp[i][0] = dp[i - 1][0] + s1[i - 1];
}
for(int j = 1; j <= n2; j++){
dp[0][j] = dp[0][j - 1] + s2[j - 1];
}
//equation
for(int i = 1; i <= n1; i++){
for(int j = 1; j <= n2; j++){
if(s1[i - 1] == s2[j - 1]){
dp[i][j] = dp[i - 1][j - 1];
}
else{
dp[i][j] = min(dp[i - 1][j] + s1[i - 1],
dp[i][j - 1] + s2[j - 1]);
}
}
}
return dp[n1][n2];
}
};