# 如何在 Python 中递归期间使用共享变量

#### How to use a shared variable during Recursion in Python

``````class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if not grid:
return

R = len(grid)
C = len(grid[0])
min_path = None

def backtrack(grid, i, j, current_path):

if i >= R or j>= C:
return
current_path += grid[i][j]
if i == R-1 and j == C-1:
if not min_path:
min_path = current_path
else:
min_path = min(min_path, current_path)
print(min_path)
return
backtrack(grid, i, j+1, current_path)
backtrack(grid, i+1, j, current_path)

backtrack(grid, 0, 0,0)

return min_path
``````

2 个回复

1. 将 min_path 定义为 backtrack 方法中的局部变量（这可能会导致其他问题，因为您正在递归调用它）：
``````class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if not grid:
return

R = len(grid)
C = len(grid)
min_path_main = None

min_path_main = backtrack(grid, 0, 0,0)

return min_path_main

def backtrack(grid, i, j, current_path):
min_path = None
if i >= R or j>= C:
break
current_path += grid[i][j]
if i == R-1 and j == C-1:
if not min_path:
min_path = current_path
else:
min_path = min(min_path, current_path)
print(min_path)
break
# it's possible you'll need extra logic here to manage the output.
output1 = backtrack(grid, i, j+1, current_path)
output2 = backtrack(grid, i+1, j, current_path)

return min_path
``````
1. 将变量定义为 class 变量：
``````class Solution:
def __init__(self):
self.min_path = None

def minPathSum(self, grid: List[List[int]]) -> int:
if not grid:
return

R = len(grid)
C = len(grid)

backtrack(grid, 0, 0,0)

return self.min_path

def backtrack(grid, i, j, current_path):
if i >= R or j>= C:
break
current_path += grid[i][j]
if i == R-1 and j == C-1:
if not self.min_path:
self.min_path = current_path
else:
self.min_path = min(self.min_path, current_path)
print(self.min_path)
break
backtrack(grid, i, j+1, current_path)
backtrack(grid, i+1, j, current_path)

return
``````

``````def min_sum(g):
if not g or not g[0]:
return float('inf')
return g[0][0] + ((len(g) > 1 or len(g[0]) > 1) and min(map(min_sum, (g[1:], [*zip(*g)][1:]))))
``````

``````min_sum([
[1,3,1],
[1,5,1],
[4,2,1]
])
``````

1 Python递归期间的内存使用

3 Python递归期间的变量范围错误

2011-11-20 15:28:32 3 867   scope
4 如何在python中使用递归

5 如何在递归中使用索引变量？

6 递归期间的全局变量

7 如何在python中递归期间保持状态

2020-02-16 15:53:15 2 158   state
8 如何创建和使用共享 memory 项的两个 Python 迭代，并在使用过程中维护共享 memory？

9 在python中使用递归来组合可变大小的列表

10 Python多重处理：如何将共享变量用于复杂类的列表？