- 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
- 42 lines of Python from the credited upstream file number-of-zigzag-arrays-iii.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 zigZagArrays(self, n, l, r):7 """8 :type n: int9 :type l: int10 :type r: int11 :rtype: int12 """13 MOD = 10**9+714 inv, inv_fact = [[1]*2 for _ in xrange(2)]15 def inv_factorial(n):16 while len(inv) <= n: 17 inv.append(inv[MOD%len(inv)]*(MOD-MODlen(inv)) % MOD) 18 inv_fact.append(inv_fact[-1]*inv[-1] % MOD)19 return inv_fact[n]20 21 def f(x):22 dp = range(x)23 for _ in xrange(n-2):24 new_up = [0]*x25 for i in xrange(x-1):26 new_up[i+1] = (new_up[i]+dp[~i])%MOD27 dp = new_up28 return (reduce(lambda accu, x: (accu+x)%MOD, dp, 0)*2)%MOD29 30 m = r-l+131 if m <= n+1:32 return f(m)33 prefix = [0]*((n+1)+1)34 prefix[0] = 135 for i in xrange(len(prefix)-1):36 prefix[i+1] = prefix[i]*(m-1-i)%MOD37 suffix = [0]*((n+1)+1)38 suffix[-1] = 139 for i in reversed(xrange(len(suffix)-1)):40 suffix[i] = suffix[i+1]*(m-1-i)%MOD41 return reduce(lambda accu, x: (accu+x)%MOD, (f(i+1)*(prefix[i]*suffix[i+1])*(inv_factorial(i)*inv_factorial(n-i)*(-1 if (n-i)%2 else 1)) for i in xrange(n+1)), 0)42