LeetCode 第 63 题:不同路径 II(动态规划)

地址:https://leetcode-cn.com/problems/unique-paths-ii/

Java 代码:

public class Solution {

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int rows = obstacleGrid.length;
        if (rows == 0) {
            return 0;
        }

        int cols = obstacleGrid[0].length;
        int[][] dp = new int[rows][cols];

        // 如果一开始就遇到障碍,就没有必要进行下去了
        if (obstacleGrid[0][0] == 1) {
            return 0;
        } else {
            dp[0][0] = 1;
        }

        // 先把第 0 行写了
        for (int j = 1; j < cols && obstacleGrid[0][j] == 0; j++) {
            dp[0][j] = 1;
        }

        // 再把第 0 列写了
        for (int i = 1; i < rows && obstacleGrid[i][0] == 0; i++) {
            dp[i][0] = 1;
        }

        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                } else {
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                }
            }
        }
        return dp[rows - 1][cols - 1];
    }
}

可以设置一个哨兵的行和列,这样就可以避免分类讨论。

Java 代码:

public class Solution {

    // 状态压缩 + 哨兵技巧
    // 空间复杂度:O(N),N 是矩阵的列数

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        if (m == 0) {
            return 0;
        }
        int n = obstacleGrid[0].length;
        int[] dp = new int[n + 1];

        // 技巧:回避了对边界条件的判断
        dp[1] = 1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[j + 1] = 0;
                } else {
                    dp[j + 1] += dp[j];
                }
            }
        }
        return dp[n];
    }
}
发布了442 篇原创文章 · 获赞 330 · 访问量 123万+

猜你喜欢

转载自blog.csdn.net/lw_power/article/details/103779239
今日推荐