我試圖解決一個面試問題:在N * N矩陣中的所有可能的路徑 - 蟒蛇
給定一個N * N矩陣,假設你開始在左上角單元格(即0,0)。您可以向右或向下移動,並且必須前往右下角的單元格。獲取小於給定值的最大值。例如,假設3 * 3矩陣,給定值爲
5
。
0 1 2
2 1 2
3 2 1
optimal path is 0 -> 1 -> 1 -> 2 -> 1 = 5
我開始使用遞歸的編碼,但答案是不正確的。有什麼建議麼?
def findAllPaths(currX, currY, path, grid, sum):
#print currX, currY
if currX == len(grid)-1:
i = currY
temp = 0
while i < len(grid):
path = path + str(grid[currX][i])
temp += grid[currX][i]
i += 1
sum.append(temp)
#print 'first loop', sum, path
return
if currY == len(grid)-1:
i = currX
temp = 0
while i < len(grid):
path = path + str(grid[i][currY])
temp += grid[i][currY]
i += 1
sum.append(temp)
#print 'second loop', sum, path
return
#print currX, currY
#path = path + str(grid[currX][currY])
findAllPaths(currX+1,currY,path,grid, sum)
findAllPaths(currX, currY+1,path,grid, sum)
return sum