简体   繁体   English

while循环内的递归

[英]recursion within a while loop

I am working on a leetcode problem Reconstruct Itinerary , here is a very concise and accepted answer , which is also pasted below.我正在处理一个 leetcode 问题Reconstruct Itinerary ,这里有一个非常简洁和公认的答案,也粘贴在下面。 I usually use recursion inside a for loop.我通常在 for 循环中使用递归。 I don't understand how exactly the visit works and why it outputs the reversed of the itinerary?我不明白这次visit究竟是如何工作的,为什么它会输出相反的行程? Could you please help me digest this code?你能帮我消化这段代码吗? I never used recursion in while loop before and it may have certain advantages over that in for loop.我之前从未在 while 循环中使用过递归,它可能比 for 循环中的递归具有某些优势。

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        graph=collections.defaultdict(list)
        for edge in tickets:
            graph[edge[0]].append(edge[1])
        for i in graph:
            graph[i].sort(reverse=True)
        ans=[]

        def visit(current):
            while graph[current]:
                visit(graph[current].pop())
            ans.append(current)
            print(ans,current)  # This line added by me

        visit("JFK")
        return ans[::-1]
test case: 
    tickets = [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
output:
    ans[::-1] 
      ['JFK', 'NRT', 'JFK', 'KUL']

Imagine a tree where each node has a variable number of children.想象一棵树,其中每个节点都有可变数量的子节点。 It could be 0 or 10,000 or any other non negative integer.它可以是 0 或 10,000 或任何其他非负 integer。 The while loop is simply traversing each child node of node current . while 循环只是遍历节点current的每个子节点。 Observe that请注意

while graph [current] 

is true while the list is nonempty.当列表非空时为真。 Each element of the list at current is passed to the next level of recursion at the call site by popping the next element. current列表的每个元素通过弹出下一个元素传递到调用站点的下一个递归级别。 Specifically具体来说

graph[current].pop()

simultaneously removes the element from the list and passes to the next level of recursion.同时从列表中删除元素并传递到下一级递归。

ans is in reverse order because all nodes are fully explored depth first before the current node is appended. ans是相反的顺序,因为在附加当前节点之前,所有节点都首先完全探索深度。 You can see this by moving你可以通过移动看到这个

ans.append(current)

To before the while loop.while循环之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM