class Solution:
def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:
G = [[] for _ in range(n)]
for edge in edges:
G[edge[0]].append(edge[1])
G[edge[1]].append(edge[0])
ans = 0
def dfs(i:int,f:int)->tuple[int, int]:
nonlocal ans
max_path1 = price[i]
max_path2 = 0
for j in G[i]:
if j != f:
path_tuple = dfs(j,i)
ans = max(path_tuple[0] + max_path2,ans)
ans = max(path_tuple[1] + max_path1,ans)
max_path1 = max(max_path1,path_tuple[0] + price[i])
max_path2 = max(max_path2,path_tuple[1] + price[i])
return (max_path1,max_path2)
dfs(0,-1)
return ans
关于#lc-2538#的问题:nonlocal ans
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
阿里嘎多学长 2025-04-15 10:14关注阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程
问题解答
问题是 LeetCode 2538 中的非本地变量
ans问题。问题描述:给定一个图,图中每个节点都有一个价格,图中每个边都有一个权重。现在,我们需要在图中找到一个路径,使得路径上的总价格最大。
解决方案:使用深度优先搜索(DFS)来解决这个问题。我们可以使用一个变量
ans来存储当前路径的总价格,然后在 DFS 遍历过程中不断更新ans。以下是 Python 代码:
class Solution: def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int: graph = [[] for _ in range(n)] for edge in edges: graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) ans = 0 def dfs(node, path_price): nonlocal ans ans = max(ans, path_price) for neighbor in graph[node]: if neighbor not in path: dfs(neighbor, path_price + price[neighbor]) path = [] dfs(0, price[0]) return ans在上面的代码中,我们首先构建了一个图,然后使用 DFS 遍历图,更新
ans变量。最后,我们返回ans变量的值,即最大路径的总价格。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报