
Sponsored
Sponsored
This approach involves using a 2D table to compute the minimum ASCII delete sum to make the two strings equal. The table is filled using a bottom-up dynamic programming method, considering the cost of deleting characters from either string.
For each index pair (i, j), we decide whether to delete a character from either s1 or s2 or take the sum from previously computed states to minimize the ASCII sum deletion cost.
Time Complexity: O(m * n), where m and n are the lengths of s1 and s2. This is because we need to fill the entire DP table.
Space Complexity: O(m * n), due to storage in a 2D table.
1def minimumDeleteSum(s1: str, s2: str) -> int:
2 m, n = len(s1), len(s2)
3 dp = [[0] * (n + 1) for _ in range(m + 1)]
4
5 # Fill the last column
6 for i in range(m-1, -1, -1):
7 dp[i][n] = dp[i+1][n] + ord(s1[i])
8
9 # Fill the last row
10 for j in range(n-1, -1, -1):
11 dp[m][j] = dp[m][j+1] + ord(s2[j])
12
13 # Fill the rest of dp table
14 for i in range(m-1, -1, -1):
15 for j in range(n-1, -1, -1):
16 if s1[i] == s2[j]:
17 dp[i][j] = dp[i+1][j+1]
18 else:
19 dp[i][j] = min(dp[i+1][j] + ord(s1[i]), dp[i][j+1] + ord(s2[j]))
20
21 return dp[0][0]
22This solution defines a 2D DP table where dp[i][j] represents the minimum ASCII delete sum to make the substrings s1[i:] and s2[j:] equal. We pre-compute the additional cost of deleting each character from the end of the strings and use these results to fill the DP table iteratively. If characters at positions i and j are equal, we take the diagonal value; otherwise, we take the minimum cost of deleting either character.
This approach uses a recursive function with memoization to solve the problem. The recursive function computes the minimum ASCII sum by exploring all possible deletions and storing intermediate results to avoid redundant calculations. This can be a more intuitive approach for those familiar with recursion at the expense of higher time complexity when not optimized with memoization.
Time Complexity: O(m * n) due to memoization reducing the duplicate calculations.
Space Complexity: O(m * n), with space used for the recursion stack and memoization storage.
1#include <string.h>
2
The C solution employs a 2D DP array similar to the dynamic programming approach. It iteratively fills the table considering ASCII values of characters to minimize deletions. The solution handles character comparison and deletion tracking using basic arrays.