- 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
- 75 lines of Python from the credited upstream file count-ways-to-choose-coprime-integers-from-rows.py.
- The implementation visibly relies on sequence storage, hash lookup, 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 4import collections5 6 78class Solution(object):9 def countCoprime(self, mat):10 """11 :type mat: List[List[int]]12 :rtype: int13 """14 MOD = 10**9+715 def linear_sieve_of_eratosthenes(n): 16 primes = []17 spf = [-1]*(n+1) 18 for i in xrange(2, n+1):19 if spf[i] == -1:20 spf[i] = i21 primes.append(i)22 for p in primes:23 if i*p > n or p > spf[i]:24 break25 spf[i*p] = p26 return spf27 28 29 def mobius(spf): 30 mu = [0]*len(spf)31 for i in xrange(1, len(mu)):32 mu[i] = 1 if i == 1 else 0 if spf[ispf[i]] == spf[i] else -mu[ispf[i]]33 return mu34 35 mx = max(max(row) for row in mat)36 mu = mobius(linear_sieve_of_eratosthenes(mx))37 dp = [1]*(mx+1)38 for row in mat:39 cnt = collections.defaultdict(int)40 for x in row:41 cnt[x] += 142 for i in xrange(1, mx+1):43 dp[i] = (dp[i]*reduce(lambda accu, x: (accu+x)%MOD, (cnt[j] for j in xrange(i, mx+1, i)), 0))%MOD44 return reduce(lambda accu, x: (accu+x)%MOD, (dp[i]*mu[i] for i in xrange(1, mx+1)), 0)45 46 474849import collections50 51 5253class Solution2(object):54 def countCoprime(self, mat):55 """56 :type mat: List[List[int]]57 :rtype: int58 """59 MOD = 10**9+760 def gcd(a, b):61 while b:62 a, b = b, a%b63 return a64 65 dp = collections.defaultdict(int)66 dp[0] = 167 for row in mat:68 new_dp = collections.defaultdict(int)69 for x in row:70 for g, c in dp.iteritems():71 ng = gcd(g, x)72 new_dp[ng] = (new_dp[ng]+c)%MOD73 dp = new_dp74 return dp[1]75