712. Minimum ASCII Delete Sum for Two Strings(DP)

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];
        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值