- 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
- 74 lines of Python from the credited upstream file minimum-cost-to-convert-string-iii.py.
- The implementation visibly relies on sequence storage, 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 45class Solution(object):6 def minCost(self, source, target, rules, costs):7 """8 :type source: str9 :type target: str10 :type rules: List[List[str]]11 :type costs: List[int]12 :rtype: int13 """14 INF = float("inf")15 w = min(max(r for _, r in rules), len(source))+116 dp = [INF]*w17 dp[0] = 018 for i in xrange(len(source)):19 dp[(i-1)%w] = INF20 if dp[i%w] is INF:21 continue22 if source[i] == target[i]:23 dp[(i+1)%w] = min(dp[(i+1)%w], dp[i%w])24 for j, (p, r) in enumerate(rules):25 c = costs[j]26 if i+len(p) >= len(source)+1:27 continue28 for k in xrange(len(p)):29 if r[k] != target[i+k]:30 break31 if p[k] == '*':32 c += 133 elif p[k] != source[i+k]:34 break35 else:36 dp[(i+len(p))%w] = min(dp[(i+len(p))%w], dp[i%w]+c)37 return dp[len(source)%w] if dp[len(source)%w] is not INF else -138 39 40414243class Solution2(object):44 def minCost(self, source, target, rules, costs):45 """46 :type source: str47 :type target: str48 :type rules: List[List[str]]49 :type costs: List[int]50 :rtype: int51 """52 INF = float("inf")53 dp = [INF]*(len(source)+1)54 dp[0] = 055 for i in xrange(len(source)):56 if dp[i] is INF:57 continue58 if source[i] == target[i]:59 dp[i+1] = min(dp[i+1], dp[i])60 for j, (p, r) in enumerate(rules):61 c = costs[j]62 if i+len(p) >= len(dp):63 continue64 for k in xrange(len(p)):65 if r[k] != target[i+k]:66 break67 if p[k] == '*':68 c += 169 elif p[k] != source[i+k]:70 break71 else:72 dp[i+len(p)] = min(dp[i+len(p)], dp[i]+c)73 return dp[-1] if dp[-1] is not INF else -174