Version #2 DP Space O(N)
55.15 %
class Solution {
public int minimumDeleteSum(String s1, String s2) {
// dp[i][j] min to match s1[0,i) s2[0,j)
int[] dp = new int[s2.length() + 1];
int prev = 0;
int curr = 0;
for (int i = 0; i <= s1.length(); i++) {
for (int j = 0; j <= s2.length(); j++) {
if (i == 0 && j == 0) {
dp[j] = 0;
} else if (i == 0) { // 1st row
dp[j] = dp[j - 1] + (int) s2.charAt(j - 1);
} else if (j == 0) { // 1st column
curr = dp[j];
dp[j] += (int) s1.charAt(i - 1); // accumulate last row's 1st column
} else {
curr = dp[j];
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[j] = prev;
} else {
dp[j] = Math.min(dp[j] + (int) s1.charAt(i - 1),
dp[j - 1] + (int) s2.charAt(j - 1));
}
}
prev = curr;
}
}
return dp[s2.length()];
}
}
Version #1 DP Space O(MN)
64.38 %
class Solution {
public int minimumDeleteSum(String s1, String s2) {
// dp[i][j] min to match s1[0,i) s2[0,j)
int[][] dp = new int[s1.length() + 1][s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
for (int j = 0; j <= s2.length(); j++) {
if (i == 0 && j == 0) {
dp[i][j] = 0;
} else if (i == 0) {
dp[i][j] = dp[i][j - 1] + (int) s2.charAt(j - 1);
} else if (j == 0) {
dp[i][j] = dp[i - 1][j] + (int) s1.charAt(i - 1);
} else {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j] + (int) s1.charAt(i - 1),
dp[i][j - 1] + (int) s2.charAt(j - 1));
}
}
}
}
return dp[s1.length()][s2.length()];
}
}
No comments:
Post a Comment