Approach
Depth-first search
For Count Connected Subgraphs with Even Node Sum, 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
- 75 lines of Python from the credited upstream file count-connected-subgraphs-with-even-node-sum.py.
- The implementation visibly relies on sequence storage.
- 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 45class Solution(object):6 def evenSumSubgraphs(self, nums, edges):7 """8 :type nums: List[int]9 :type edges: List[List[int]]10 :rtype: int11 """12 def even(mask):13 def popcount(x):14 return bin(x).count('1')15 16 return not popcount(mask&odd_mask)%217 18 def connected(mask):19 i = next(i for i in xrange(len(nums)) if mask&(1<<i))20 mask ^= 1<<i21 stk = [i]22 while stk:23 u = stk.pop()24 for v in adj[u]:25 if not mask&(1<<v):26 continue27 mask ^= 1<<v28 stk.append(v)29 return not mask30 31 adj = [[] for _ in xrange(len(nums))]32 for u, v in edges:33 adj[u].append(v)34 adj[v].append(u)35 odd_mask = reduce(lambda accu, x: accu|(1<<x), (i for i in xrange(len(nums)) if nums[i]), 0)36 return sum(even(mask) and connected(mask) for mask in xrange(1, 1<<len(nums)))37 38 39404142class Solution2(object):43 def evenSumSubgraphs(self, nums, edges):44 """45 :type nums: List[int]46 :type edges: List[List[int]]47 :rtype: int48 """49 def even(mask):50 parity = 051 for i in xrange(len(nums)):52 if not mask&(1<<i):53 continue54 parity ^= nums[i]55 return not parity56 57 def connected(mask):58 i = next(i for i in xrange(len(nums)) if mask&(1<<i))59 mask ^= 1<<i60 stk = [i]61 while stk:62 u = stk.pop()63 for v in adj[u]:64 if not mask&(1<<v):65 continue66 mask ^= 1<<v67 stk.append(v)68 return not mask69 70 adj = [[] for _ in xrange(len(nums))]71 for u, v in edges:72 adj[u].append(v)73 adj[v].append(u)74 return sum(even(mask) and connected(mask) for mask in xrange(1, 1<<len(nums)))75