1 回答

TA貢獻1825條經驗 獲得超6個贊
對于不需要遞歸的“更好”實現,請從右下方開始。
如果你這樣做,你只需要記住一行(或一列),所以它既更快又需要更少的內存。
例子
讓我們使用這樣的網格。為了不與下面的路徑計數數組混淆,使用符號而不是數字來定義網格。
. . . . .
. * * . .
. . . . .
. . . . .
現在為最后一行構建一個數組,其中有多少種方法可以從那里退出。
. . . . . last row from grid
=========
1 1 1 1 1 pathCount from each cell to the end
對其上方的行重復該操作。從右開始計算,pathCount為向右走時的pathCount + 向下走時的pathCount。
. . . . . 3rd row from grid
1 1 1 1 1 result from last row
=========
5 4 3 2 1 result for 3rd row
因為完成后我們不再需要最后一行的值,所以我們可以重用數組并替換內聯值。
再重復一次。這次我們屏蔽了單元格,因此將這些單元格的 pathCount 設置為 0。
. * * . . 2nd row from grid
5 4 3 2 1 result from 3rd row
=========
5 0 0 3 1 result for 2nd row
最后:
. . . . . 1st row from grid
5 0 0 3 1 result from 2nd row
=========
9 4 4 4 1 result for 1st row
最終結果:從左上角到右下角的 9 條獨特路徑。
使用網格的替代格式的緊湊實現,以便于測試:
static int countPaths(String... grid) {
int[] paths = new int[grid[0].length() + 1];
paths[grid[0].length() - 1] = 1;
for (int y = grid.length - 1; y >= 0; y--)
for (int x = grid[0].length() - 1; x >= 0; x--)
paths[x] = (grid[y].charAt(x) != '0' ? 0 : paths[x] + paths[x + 1]);
return paths[0];
}
測試
System.out.println(countPaths("00000",
"01100",
"00000",
"00000")); // prints: 9
System.out.println(countPaths("000",
"000",
"000")); // prints: 6
添加回答
舉報