1. 程式人生 > 實用技巧 >LeetCode63. 不同路徑 II

LeetCode63. 不同路徑 II

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length, n = obstacleGrid[0].length;
        // dp[i][j] 表示 (0,0) 到 (i,j)的路徑總數
        int[][] dp = new int[m][n];
        if (obstacleGrid[0][0] == 1) return 0;
        for (int i = 0; i < m; i++) {
            
for (int j = 0; j < n; j++) { // (i,j)本身有障礙物,則任何路徑都到達不了,dp[i][j] = 0 if (obstacleGrid[i][j] == 1) { continue; } if (i == 0 && j == 0) { dp[i][j] = 1; }else if (i == 0) { dp[
0][j] = dp[0][j-1]; }else if (j == 0) { dp[i][0] = dp[i-1][0]; }else { // (i,j)只能由(i-1,j)和(i,j-1)走到。 dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } } return dp[m-1][n-1];
/** * 優化:滾動陣列。 */ /* int m = obstacleGrid.length, n = obstacleGrid[0].length; // 一維陣列即可,按行更新。 int[] dp = new int[n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (obstacleGrid[i][j] == 1) { dp[j] = 0; continue; } if (i == 0 && j == 0) { dp[0] = 1; }else if (j != 0){ dp[j] += dp[j-1]; } } } return dp[n-1]; */ } }