【问题标题】:In place modification through recursion通过递归就地修改
【发布时间】:2021-12-05 02:10:26
【问题描述】:

关于以下 leetcode 问题 #210,我尝试通过对堆栈进行就地修改来创建更精简的 DFS 算法,如下所示:

numCourses = 2
prerequisites = [[1,0]]

class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: List[int]
        """
        
        stack = []
        self.dfs(prerequisites, 0, stack)
        return stack.reverse()
    
    def dfs(self, prereqs, node, stack):
        for courses in prereqs:
            if node == courses[1] and courses[0] not in stack:
                self.dfs(prereqs, courses[0], stack)
        stack.append(node)

但是,当我在findOrder 函数中返回堆栈时,它返回一个空列表。即使在我调试时,它也显示堆栈已更新为值[0,1],但是当我返回它时,它返回空列表。

我想知道在尝试通过递归对列表进行就地修改时是否会遗漏任何含义。

【问题讨论】:

  • stack.reverse() 返回None,而不是反向堆栈。
  • 不能返回空列表。

标签: python recursion depth-first-search list-manipulation


【解决方案1】:

您只需返回您的stack 列表而不是stack.reverse()。正如 cmets 中指出的那样,.reverse() 返回 None 而不是反向列表。

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多