description:
712 | Minimum ASCII Delete Sum for Two Strings Dynamic Programming | 50.6% | Medium |
my solution:
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
//i is the length of s1
//j is the length of s2
//dp[i][j] = min(dp[i-1][j] + s1[i], dp[i][j-1] + s2[j])
int m = s1.length(), n = s2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int j = 1; j < n + 1; j++) dp[0][j] = dp[0][j-1] + s2[j-1];
for (int i = 1; i < m + 1; i++) {
dp[i][0] = dp[i - 1][0] + s1[i-1];
for (int j = 1; j < n + 1; 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[m][n];
}
};
thought:
利用动态规划求解,算是比较简单的题目了,逐渐分别增长s1和s2的长度。 别人给出了占用更少空间和长度的算法。
Better ways:
by zestypanda
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int m = s1.size(), n = s2.size();
vector<int> dp(n+1, 0);
for (int j = 1; j <= n; j++)
dp[j] = dp[j-1]+s2[j-1];
for (int i = 1; i <= m; i++) {
int t1 = dp[0];
dp[0] += s1[i-1];
for (int j = 1; j <= n; j++) {
int t2 = dp[j];
dp[j] = s1[i-1] == s2[j-1]? t1:min(dp[j]+s1[i-1], dp[j-1]+s2[j-1]);
t1 = t2;
}
}
return dp[n];
}
};