- 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
- 61 lines of Python from the credited upstream file count-no-zero-pairs-that-sum-to-n.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 45class Solution(object):6 def countNoZeroPairs(self, n):7 """8 :type n: int9 :rtype: int10 """11 dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)] 12 dp[0][0][0] = 113 start = 114 while n:15 n, d = divmod(n, 10)16 new_dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)]17 for c in xrange(2):18 for i in xrange(2):19 for j in xrange(2):20 if not dp[c][i][j]:21 continue22 for x in xrange(start, (9 if not i else 0)+1):23 for nc in xrange(2):24 y = (d+nc*10)-(c+x)25 if not (start <= y <= (9 if not j else 0)):26 continue27 new_dp[nc][i or not x][j or not y] += dp[c][i][j]28 start = 029 dp = new_dp30 return sum(dp[0][i][j] for i in xrange(2) for j in xrange(2))31 32 33343536class Solution2(object):37 def countNoZeroPairs(self, n):38 """39 :type n: int40 :rtype: int41 """42 dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)] 43 dp[0][0][0] = 144 start = 145 while n:46 n, d = divmod(n, 10)47 new_dp = [[[0]*2 for _ in xrange(2)] for _ in xrange(2)]48 for c in xrange(2):49 for i in xrange(2):50 for j in xrange(2):51 if not dp[c][i][j]:52 continue53 for x in xrange(start, (9 if not i else 0)+1):54 for y in xrange(start, (9 if not j else 0)+1):55 if (c+x+y)%10 != d:56 continue57 new_dp[(c+x+y)10][i or not x][j or not y] += dp[c][i][j]58 start = 059 dp = new_dp60 return sum(dp[0][i][j] for i in xrange(2) for j in xrange(2))61