- 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
- 55 lines of Python from the credited upstream file minimum-cost-to-partition-a-binary-string.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, s, encCost, flatCost):7 """8 :type s: str9 :type encCost: int10 :type flatCost: int11 :rtype: int12 """13 def divide_and_conquer(left, right):14 l = right-left+115 x = prefix[right+1]-prefix[left]16 result = l*x*encCost if x else flatCost17 if x and l%2 == 0:18 result = min(result, divide_and_conquer(left, (left+l2)-1)+divide_and_conquer(left+l2, right))19 return result20 21 prefix = [0]*(len(s)+1)22 for i in xrange(len(s)):23 prefix[i+1] = prefix[i]+(1 if s[i] == '1' else 0)24 return divide_and_conquer(0, len(s)-1)25 26 27282930class Solution2(object):31 def minCost(self, s, encCost, flatCost):32 """33 :type s: str34 :type encCost: int35 :type flatCost: int36 :rtype: int37 """38 l = len(s)39 while l%2 == 0:40 l = 241 result = 042 dp = []43 for left in xrange(0, len(s), l):44 x = sum(s[i] == '1' for i in xrange(left, left+l))45 dp.append((l*x*encCost if x else flatCost, x))46 while len(dp) != 1:47 new_dp = []48 l *= 249 for i in xrange(0, len(dp), 2):50 v = dp[i][0]+dp[i+1][0]51 x = dp[i][1]+dp[i+1][1]52 new_dp.append(((min(l*x*encCost, v) if x else flatCost), x))53 dp = new_dp54 return dp[0][0]55