1. 程式人生 > >LeetCode 712. Minimum ASCII Delete Sum for Two Strings [Medium]

LeetCode 712. Minimum ASCII Delete Sum for Two Strings [Medium]

原題地址

題目內容

這裡寫圖片描述

題目分析

標準的動態規劃問題,題目的意思為刪除s1,s2中的字元,使得最後s1=s2,要求使得刪除的字元的值的和最小。dp[i][j]為字串1前i個字元與字串2前j個字元相等,需要減去的字元值。當s1[i-1]=s2[j-1]時,dp[i][j]=dp[i-1][j-1].當s1[i-1]!=s2[j-1]時,有兩種選擇,一刪除s1的字元,那麼dp[i][j]=dp[i-1][j]+s1[i-1],二是刪除s2的字元,dp[i][j]=dp[i][j-1]+s2[j-1],dp[i][j]顯然是選兩者當中代價最小的。

程式碼分析

class Solution {
public
: int minimumDeleteSum(string s1, string s2) { int n = s1.size(); int m = s2.size(); int dp[n+1][m+1] = {0}; for(int i = 1; i <= m; i++){ dp[0][i] = dp[0][i-1]+s2[i-1]; } for(int i = 1; i <= n; i++){ dp[i][0] = dp[i-1][0] + s1[i-1
]; for(int j = 1; j <= m; 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[n][m]; } };