我的代码(从源到目标的所有路径)中有什么问题?
问题声明: 问题链接
给定标记为0到n -1的n个节点的定向无环图(DAG),找到从节点0到节点n -1的所有可能路径,然后以任何顺序返回。
给出图表如下:图[i]是您可以的所有节点的列表 从节点i访问(即,有一个从节点I到节点的指向边缘 图[i] [j])。
输入:
[[1,2],[3],[3],[]]
输出:
[[0,1,3],[0,2,3]]
这是我的代码:
class Solution:
def allPathsSourceTargetUtil(self, n, graph, visited, ans):
visited.append(n)
if n == len(graph)-1:
ans.append(visited)
print(ans)
else:
for i in graph[n]:
self.allPathsSourceTargetUtil(i, graph, visited, ans)
visited.pop()
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
ans = []
visited = []
n = 0
self.allPathsSourceTargetUtil(n, graph, visited, ans)
return ans
这是输入:
[[1,2],[3],[3],[]]
实际输出:
[[0,1,3],[0,2,3]]
但是我从代码中获得此输出:
[[0, 1, 3]]
[[0, 2, 3], [0, 2, 3]]
[[0],[0]]
请帮助我在此代码中找出问题。
Problem statement:
Question link
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can
visit from node i (i.e., there is a directed edge from node i to node
graph[i][j]).
Input:
[[1,2],[3],[3],[]]
Output:
[[0,1,3],[0,2,3]]
This is my code :
class Solution:
def allPathsSourceTargetUtil(self, n, graph, visited, ans):
visited.append(n)
if n == len(graph)-1:
ans.append(visited)
print(ans)
else:
for i in graph[n]:
self.allPathsSourceTargetUtil(i, graph, visited, ans)
visited.pop()
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
ans = []
visited = []
n = 0
self.allPathsSourceTargetUtil(n, graph, visited, ans)
return ans
And this is input:
[[1,2],[3],[3],[]]
And real Output:
[[0,1,3],[0,2,3]]
But I get this output from my code:
[[0, 1, 3]]
[[0, 2, 3], [0, 2, 3]]
[[0],[0]]
Please help me for find out problem in this code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论