其他分享
首页 > 其他分享> > 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];
        */
    }
}

 

标签:LeetCode63,obstacleGrid,int,路径,else,II,++,length,dp
来源: https://www.cnblogs.com/HuangYJ/p/14217088.html