- 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
- 50 lines of Python from the credited upstream file longest-palindromic-path-in-graph.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 maxLen(self, n, edges, label):7 """8 :type n: int9 :type edges: List[List[int]]10 :type label: str11 :rtype: int12 """13 def popcount(x):14 return bin(x).count('1')15 16 if len(edges) == n*(n-1)2: 17 cnt = [0]*2618 for x in label:19 cnt[ord(x)-ord('a')] += 120 return 2*sum(c2 for c in cnt)+1*any(c%2 for c in cnt)21 22 adj = [[] for _ in xrange(n)]23 for u, v in edges:24 adj[u].append(v)25 adj[v].append(u)26 dp = [[[False]*n for _ in xrange(n)]for _ in xrange(1<<n)]27 for u in xrange(n):28 dp[1<<u][u][u] = True29 for u, v in edges:30 if label[u] == label[v]:31 dp[(1<<u)|(1<<v)][min(u, v)][max(u, v)] = True32 result = 033 for mask in xrange(1, 1<<n):34 for u in xrange(n):35 for v in xrange(u, n):36 if not dp[mask][u][v]:37 continue38 result = max(result, popcount(mask))39 for nu in adj[u]:40 if mask&(1<<nu):41 continue42 for nv in adj[v]:43 if mask&(1<<nv):44 continue45 if nu == nv:46 continue47 if label[nu] == label[nv]:48 dp[mask|(1<<nu)|(1<<nv)][min(nu, nv)][max(nu, nv)] = True49 return result50