LeetCode 63. 不同路径 II

题目链接

63. 不同路径 II

题目分析

非常典型的一个DP问题。我们采用一个二维dp数组,dp[i][j]的意思是从0,0出发到obs[i][j]的路径和有多少条,注意边界值就行。
状态转移方程如下:

  • if(obs[i][j] == 0) dp[i][j] = dp[i-1][j] + dp[i][j-1]

代码实现

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid.length == 0){
            return 0;
        }
        int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length];
        for(int i = 0; i < dp.length; i++){
            if(obstacleGrid[i][0] == 1){
                break;
            }
            dp[i][0] = 1;
        }
        for(int i = 0; i < dp[0].length; i++){
            if(obstacleGrid[0][i] == 1){
                break;
            }
            dp[0][i] = 1;
        }
        for(int i = 1; i < dp.length; i++){
            for(int j = 1; j < dp[i].length; j++){
                if(obstacleGrid[i][j] == 0){
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
                }
            }
        }
        return dp[dp.length-1][dp[0].length-1];
    }
}
posted @ 2020-07-06 10:32  ZJPang  阅读(80)  评论(0编辑  收藏  举报