LeetCode 509: 斐波那契数 "int object not subscriptable"

LeetCode 509: Fibonacci Number "int object not subscriptable"

LeetCode 509: Fibonacci Number

class Solution:
    def fib(self, N: int) -> int:

        if N == 0:
            return 0
        if N == 1:
            return 1

        memo = [None] * (N+1)

        return self.recurse(N, memo)

    def recurse(self, N: int, memo: List) -> int:

        if N == 0:
            return 0
        elif N == 1:
            return 1
        elif memo[N] != None:
            return memo[N]

        memo[N] = self.recurse(N-1, N-2)

        return memo[N]

我在 "elif memo[n] != None:" 行收到 "int object not subscriptable" 错误。然而,备忘录是一个列表而不是一个整数。我不知道为什么会收到此错误。也许这与我用所有 None 元素初始化我的列表有关?任何帮助,将不胜感激。谢谢!

给你:

from typing import List

class Solution:
    def fib(self, N: int) -> int:
        if N == 0: return 0
        elif N == 1: return 1
        memo = [None] * (N+1)
        memo[0] = 0
        memo[1] = 1
        return self.recurse(N, memo)

    def recurse(self, N: int, memo: List) -> int:
        if memo[N] is not None:
            return memo[N]
        memo[N] = self.recurse(N - 1, memo) + self.recurse(N - 2, memo)
        return memo[N]

solution = Solution()
for i in range(10):
    print(f'fib({i}) = {solution.fib(i)}')

输出:

fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34