- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 52 lines of Python from the credited upstream file minimum-ascii-delete-sum-for-two-strings.py.
- The implementation visibly relies on cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution(object):5 def minimumDeleteSum(self, s1, s2):6 """7 :type s1: str8 :type s2: str9 :rtype: int10 """11 dp = [[0] * (len(s2)+1) for _ in xrange(2)]12 for j in xrange(len(s2)):13 dp[0][j+1] = dp[0][j] + ord(s2[j])14 15 for i in xrange(len(s1)):16 dp[(i+1)%2][0] = dp[i%2][0] + ord(s1[i])17 for j in xrange(len(s2)):18 if s1[i] == s2[j]:19 dp[(i+1)%2][j+1] = dp[i%2][j]20 else:21 dp[(i+1)%2][j+1] = min(dp[i%2][j+1] + ord(s1[i]), \22 dp[(i+1)%2][j] + ord(s2[j]))23 24 return dp[len(s1)%2][-1]25 26 272829class Solution2(object):30 def minimumDeleteSum(self, s1, s2):31 """32 :type s1: str33 :type s2: str34 :rtype: int35 """36 dp = [[0] * (len(s2)+1) for _ in xrange(len(s1)+1)]37 for i in xrange(len(s1)):38 dp[i+1][0] = dp[i][0] + ord(s1[i])39 for j in xrange(len(s2)):40 dp[0][j+1] = dp[0][j] + ord(s2[j])41 42 for i in xrange(len(s1)):43 for j in xrange(len(s2)):44 if s1[i] == s2[j]:45 dp[i+1][j+1] = dp[i][j]46 else:47 dp[i+1][j+1] = min(dp[i][j+1] + ord(s1[i]), \48 dp[i+1][j] + ord(s2[j]))49 50 return dp[-1][-1]51 52