当前位置: 首页> 科技> 互联网 > Python | Leetcode Python题解之第399题除法求值

Python | Leetcode Python题解之第399题除法求值

时间:2025/7/11 1:02:27来源:https://blog.csdn.net/Mopes__/article/details/142155396 浏览次数:0次

题目:

题解:

class Solution:def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:# 构造图graph = defaultdict(list)for (u, v), value in zip(equations, values):graph[u].append((v, value))graph[v].append((u, 1 / value))def dfs(node, target, visited, acc_product):# 如果找到了目标节点,返回累积乘积if node == target:return acc_product# 标记当前节点为已访问visited.add(node)# 遍历当前节点的邻居for neighbor, value in graph[node]:if neighbor not in visited:result = dfs(neighbor, target, visited, acc_product * value)if result != -1:return resultreturn -1results = []for start, end in queries:if start in graph and end in graph:# 如果起点和终点都在图中,进行DFSresults.append(dfs(start, end, set(), 1.0))else:# 否则,结果为-1results.append(-1.0)return results
关键字:Python | Leetcode Python题解之第399题除法求值

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: