-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_712
32 lines (31 loc) · 991 Bytes
/
leetcode_712
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
//使用dp的思想
//dp[i][j]:s1中前i个数和s2中前j个数删除所需的最小cost
/*
dp[i][j]=|dp[i-1][j-1] if s1[i]==s2[j]
*/ // |min(dp[i-1][j]+s1[i],dp[i][j-1]+s2[j])
int m=s1.length();
int n=s2.length();
vector<vector<int>> dp_vec;
dp_vec.resize(m+1);
for(int i=0;i<=m;i++)
dp_vec[i].resize(n+1);
for(int i=1;i<=m;i++)
dp_vec[i][0]=dp_vec[i-1][0]+s1[i-1];
for(int j=1;j<=n;j++)
dp_vec[0][j]=dp_vec[0][j-1]+s2[j-1];
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s1[i-1]==s2[j-1])
dp_vec[i][j]=dp_vec[i-1][j-1];
else
dp_vec[i][j]=min(dp_vec[i-1][j]+s1[i-1],dp_vec[i][j-1]+s2[j-1]);
}
}
return dp_vec[m][n];
}
};