我在'helper'函数之外声明了一个变量'gmax'。 我在辅助函数中做了“ global gmax”。 但是仍然说变量gmax未定义。
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
gmax = float('inf')
def helper(row,col,cur_sum):
global gmax
if row==len(triangle):
if gmax > cur_sum:
gmax = cur_sum
return
val1 = triangle[row][col]
val2 = triangle[row][col+1] if col+1<len(triangle[row]) else float('inf')
cur_sum += min(val1,val2)
idx = col if val1<val2 else col+1
helper(row+1, idx, cur_sum)
helper(0,0,0)
return gmax
输出显示'第7行:名称'gmax'未定义'
答案 0 :(得分:0)
gmax
离开班级时运行。
gmax = float('inf') # global variable is outside
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
def helper(row, col, cur_sum):
global gmax
if row == len(triangle):
if gmax > cur_sum:
gmax = cur_sum
return
val1 = triangle[row][col]
val2 = triangle[row][col + 1] if col + 1 < len(triangle[row]) else float('inf')
cur_sum += min(val1, val2)
idx = col if val1 < val2 else col + 1
helper(row + 1, idx, cur_sum)
helper(0, 0, 0)
return gmax