Approach
Depth-first search
For Maximum Good Subtree Score, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 111 lines of Python from the credited upstream file maximum-good-subtree-score.py.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 goodSubtreeSum(self, vals, par):10 """11 :type vals: List[int]12 :type par: List[int]13 :rtype: int14 """15 MOD = 10**9+716 def get_mask(x):17 mask = 018 while x:19 x, d = divmod(x, 10)20 if mask&(1<<d):21 return -122 mask |= 1<<d23 return mask24 25 def iter_dfs():26 result = 027 ret = collections.defaultdict(int)28 stk = [(1, (0, ret))]29 while stk:30 step, args = stk.pop()31 if step == 1:32 u, ret = args33 ret[0] = 034 mask = get_mask(vals[u])35 if mask != -1:36 ret[mask] = vals[u]37 stk.append((4, (u, ret)))38 stk.append((2, (u, 0, ret)))39 elif step == 2:40 u, i, ret = args41 if i == len(adj[u]):42 continue43 v = adj[u][i]44 stk.append((2, (u, i+1, ret)))45 new_ret = collections.defaultdict(int)46 stk.append((3, (new_ret, ret)))47 stk.append((1, (v, new_ret)))48 elif step == 3:49 new_ret, ret = args50 for m1, v1 in ret.items():51 for m2, v2 in new_ret.iteritems():52 if m1&m2:53 continue54 ret[m1|m2] = max(ret[m1|m2], v1+v2)55 elif step == 4:56 u, ret = args57 result = (result+max(ret.itervalues()))%MOD58 return result59 60 adj = [[] for _ in xrange(len(vals))]61 for u in xrange(1, len(par)):62 adj[par[u]].append(u)63 return iter_dfs()64 65 666768import collections69 70 7172class Solution2(object):73 def goodSubtreeSum(self, vals, par):74 """75 :type vals: List[int]76 :type par: List[int]77 :rtype: int78 """79 MOD = 10**9+780 def get_mask(x):81 mask = 082 while x:83 x, d = divmod(x, 10)84 if mask&(1<<d):85 return -186 mask |= 1<<d87 return mask88 89 def dfs(u):90 dp = collections.defaultdict(int)91 dp[0] = 092 mask = get_mask(vals[u])93 if mask != -1:94 dp[mask] = vals[u]95 for v in adj[u]:96 new_dp = dfs(v)97 for m1, v1 in dp.items():98 for m2, v2 in new_dp.iteritems():99 if m1&m2:100 continue101 dp[m1|m2] = max(dp[m1|m2], v1+v2)102 result[0] = (result[0]+max(dp.itervalues()))%MOD103 return dp104 105 adj = [[] for _ in xrange(len(vals))]106 for u in xrange(1, len(par)):107 adj[par[u]].append(u)108 result = [0]109 dfs(0)110 return result[0]111