I declared a variable 'gmax' outside of 'helper' function. And I did 'global gmax' inside helper function. But still it says variable gmax undefined.
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
Output says 'Line 7: name 'gmax' is not defined'
It ran when gmax
got out of the class.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.