我用Python解决了lintcode中的paint fence问题。在python代码中,我定义了一个只包含4个元素的列表,并运行循环以根据递归方程更新最后三个元素,但提交失败并告诉我"内存限制超过"。这是代码:
class Solution:
# @param {int} n non-negative integer, n posts
# @param {int} k non-negative integer, k colors
# @return {int} an integer, the total number of ways
def numWays(self, n, k):
# Write your code here
table = [0, k, k*k, 0]
if n <= 2:
return table[n]
# recurrence equation
# table[posts] = (color - 1) * (table[posts - 1] + table[posts - 2])
for i in range(3, n + 1):
table[3] = (k - 1) * (table[1] + table[2])
table[1], table[2] = table[2], table[3]
return table[3]
我在这段代码中没有发现任何错误。有人能帮我解决一下吗?