在Python中没有定义全局名称助手,即使存在函数

2024-04-26 02:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理这个问题https://leetcode.com/problems/climbing-stairs,得到一个错误“global name helper is not defined”。但它是在类中定义的?你知道吗

class Solution(object):
    def climbStairs(self, n, ):
        """
        :type n: int
        :rtype: int
        """

        return helper(0, n)

    def helper(self, curr, n):
        if (curr > n):
            return 0

        if (curr == n):
            return 1

        return helper(curr + 1, n) + helper(curr + 2, n)

Tags: httpsselfhelpercomreturnifdef错误
2条回答

helperSolution实例的绑定函数,需要在self上调用它。你知道吗

根据较大输入上的超时错误,这是因为每次调用helper都要进行2次递归调用,这意味着运行时复杂性为O(2^N)。你知道吗

因为许多调用都具有相同的参数,所以可以使用^{}缓存以前调用的结果,从而将其减少到O(N)

from functools import lru_cache

class Solution(object):
    def climbStairs(self, n, ):
        """
        :type n: int
        :rtype: int
        """

        return self.helper(0, n)

    @lru_cache()
    def helper(self, curr, n):
        if (curr > n):
            return 0

        if (curr == n):
            return 1

        return self.helper(curr + 1, n) + self.helper(curr + 2, n)


s = Solution()
print(s.climbStairs(35))

您缺少helper的'self'参数,即将helper()替换为自助服务()应该是可行的。你知道吗


class Solution(object):
    def climbStairs(self, n, ):
        """
        :type n: int
        :rtype: int
        """

        return self.helper(0, n)

    def helper(self, curr, n):
        if (curr > n):
            return 0

        if (curr == n):
            return 1

        return self.helper(curr + 1, n) + self.helper(curr + 2, n)

相关问题 更多 >