https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/
Solution 1.
int minimumDeleteSum(string s1, string s2) {
int m = s1.size(), n = s2.size();
vector<vector<int>> dp(m+1, vector<int> (n+1, 0));
dp[0][0] = 0;
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++) dp[0][j] = dp[0][j-1] + s2[j-1];
for(int i=1; i<m+1; i++) {
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];
}
Solution 2. Use recursion. Much slower.
int minimumDeleteSum(string s1, string s2) {
if(s1.size() == 0) {
int sm = 0;
for(char c: s2) sm += c;
return sm;
}
if(s2.size() == 0) {
int sm = 0;
for(char c: s1) sm += c;
return sm;
}
vector<vector<int>> dp(s1.size()+1, vector<int> (s2.size()+1, -1));
return minSum(s1, s2, 0, 0, dp);
}
int minSum(string& s1, string& s2, int i, int j, vector<vector<int>>& dp) {
if(dp[i][j] != -1) return dp[i][j];
if(i==s1.size()) {
int j1 = j;
int sm = 0;
while(j<s2.size()) { sm += s2[j]; j++; }
dp[i][j1] = sm;
return sm;
}
else if(j==s2.size()) {
int i1 = i;
int sm = 0;
while(i<s1.size()) { sm += s1[i]; i++; }
dp[i1][j] = sm;
return sm;
}
if(s1[i]==s2[j]) dp[i][j] = minSum(s1, s2, i+1, j+1, dp);
else {
int sm1 = minSum(s1, s2, i+1, j, dp) + s1[i];
int sm2 = minSum(s1, s2, i, j+1, dp) + s2[j];
dp[i][j] = min(sm1, sm2);
}
return dp[i][j];
}
No comments:
Post a Comment