- Leetcode 3373. Maximize the Number of Target Nodes After Connecting Trees II
- 1. 接替思路
- 2. 代码实现
- 题目链接:3373. Maximize the Number of Target Nodes After Connecting Trees II
1. 接替思路
这一题和前一题Leetcode 3372其实整体思路上并没有啥太大的区别,都是考察两棵树上各自每一个节点作为根节点时满足条件的节点个数,然后相加。
唯一的区别在于,题目Leetcode 3372要求的是到根节点深度不超过 k k k,而这道题要求的是深度为偶数的节点个数,两者大差不差,都是用一个遍历即可。
但是这里由于只需要考虑奇偶性,因此我们可以用缓存来减小重复计算,优化整体的执行效率。
2. 代码实现
给出python代码实现如下:
class Solution:
def maxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]]) -> List[int]:
graph1 = defaultdict(list)
for u, v in edges1:
graph1[u].append(v)
graph1[v].append(u)
graph2 = defaultdict(list)
for u, v in edges2:
graph2[u].append(v)
graph2[v].append(u)
n, m = len(edges1) + 1, len(edges2) + 1
@lru_cache(None)
def dfs1(u, p, is_valid):
if is_valid:
if (p != -1 and len(graph1[u]) == 1) or (p == -1 and len(graph1[u]) == 0):
return 1
else:
return 1 + sum(dfs1(v, u, False) for v in graph1[u] if v != p)
else:
if (p != -1 and len(graph1[u]) == 1) or (p == -1 and len(graph1[u]) == 0):
return 0
else:
return sum(dfs1(v, u, True) for v in graph1[u] if v != p)
@lru_cache(None)
def dfs2(u, p, is_valid):
if is_valid:
if (p != -1 and len(graph2[u]) == 1) or (p == -1 and len(graph2[u]) == 0):
return 1
else:
return 1 + sum(dfs2(v, u, False) for v in graph2[u] if v != p)
else:
if (p != -1 and len(graph2[u]) == 1) or (p == -1 and len(graph2[u]) == 0):
return 0
else:
return sum(dfs2(v, u, True) for v in graph2[u] if v != p)
s1 = [dfs1(u, -1, True) for u in range(n)]
s2 = [dfs2(u, -1, False) for u in range(m)]
s = max(s2)
return [x+s for x in s1]
提交代码评测得到:耗时4387ms,占用内存386.5MB。