我很难弄清楚到底是什么导致这些功能具有不同的行为。逻辑似乎完全相同。
我尝试调试,在我看来,在第二个示例中,添加项是一次添加到两行。
def uniquePaths(self, m: int, n: int) -> int:
grid = [[1]*m] + [[0]*(m)]*(n-1)
for row in range(1, n):
for col in range(m):
if col - 1 < 0:
grid[row][col] = grid[row-1][col]
else:
grid[row][col] = grid[row-1][col] + grid[row][col-1]
return grid[-1][-1]
def uniquePaths2(self, m: int, n: int) -> int:
grid = [[1]*m] + [[0]*(m)]*(n-1)
for row in range(1, n):
for col in range(m):
if col - 1 >= 0:
grid[row][col]=grid[row][col-1]
grid[row][col] += grid[row-1][col]
return grid[-1][-1]
答案 0 :(得分:0)
您的代码中似乎存在逻辑缺陷,可能是您的功能需求。以下是这两种方法的说明:
代码1:
if col - 1 < 0:
grid[row][col] = grid[row-1][col]
else:
grid[row][col] = grid[row-1][col] + grid[row][col-1]
# Above line adds grid[row-1][col] and grid[row][col-1], and assigns to grid[row][col]
代码2:
if col - 1 >= 0:
grid[row][col]=grid[row][col-1]
grid[row][col] += grid[row-1][col]
这等效于:
if col - 1 >= 0:
grid[row][col] = grid[row][col-1] # assigning some value to this cell
grid[row][col] = grid[row][col] + grid[row-1][col] # overwriting that cell
# grid[row][col] = grid[row][col-1] + grid[row-1][col] # above two lines are equivalent to this
else:
grid[row][col] = grid[row][col] + grid[row-1][col]
希望,您会有所不同,并且可以根据需要修改代码。
答案 1 :(得分:0)
找出我初始化矩阵的方式,弄乱了代码的执行方式。
grid = [[0 for i in range(m)] for j in range(n)]
for col in range(m):
grid[0][col] = 1
if语句中的逻辑正确。 不知何故,其他初始化导致矩阵中每列的每个元素更新。
当您将它们相乘时,似乎python会复制列表,从而可能出现以下行为:
>>> grid = [[1]*m] +[[0]*(m)]*(n-1)
>>> grid
[[1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> grid[1][0] = 5
>>> grid
[[1, 1, 1, 1, 1], [5, 0, 0, 0, 0], [5, 0, 0, 0, 0]]
请注意,这两行中的5个都会更新。