找到金字塔中的最大方式

时间:2016-12-17 19:29:43

标签: python recursion

我有以下代码:

def max_trail(pyramid,row=0,col=0):
    if not pyramid:
        return 0
    if len(pyramid) == 1:
       return max(pyramid[0])
    if col >= len(pyramid[row]):
       return 0
    return (pyramid[row][col] + max(
        max_trail(pyramid[1:], row+1, col),
        max_trail(pyramid[1:], row+1, col+1)
    ))

但是对于输入: max_trail([[4],[5,7],[3,4,2],[8,3,6,1]) 我得到错误的"索引超出范围"。 我不知道该怎么办。我一定要帮忙~~

1 个答案:

答案 0 :(得分:1)

这有效:

def max_trail(pyramid, row=0, col=0):
    if len(pyramid) <= row + 1:
       return pyramid[row][col]
    return pyramid[row][col] + max(
        max_trail(pyramid, row+1, col),
        max_trail(pyramid, row+1, col+1)
    )

备忘录版本可能是:

def max_trail(pyramid, row=0, col=0, memo={}):
    if (row, col) in memo:
        return memo[(row, col)]
    if len(pyramid) <= row + 1:
        result = pyramid[row][col]
    else:
        result = pyramid[row][col] + max(
            max_trail(pyramid, row+1, col, memo),
            max_trail(pyramid, row+1, col+1, memo)
        )
    memo[(row, col)] = result
    return result