LeetCode Unique Paths II

原题链接在这里:https://leetcode.com/problems/unique-paths-ii/

Unique Paths的进阶版题目。思路与Unique Paths相似,不同点在于加了障碍物,DP的更新当前点方式有所不同, 若是此处有障碍物,res里这一点就是0,若此处没有障碍物,res里这一点就同行上一列和同列上一行的和。

Note: 初始化是点res[0][0].

AC Java:

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0){
            return 0;
        }
        int h = obstacleGrid.length;
        int w = obstacleGrid[0].length;
        int[][] res = new int[h][w];
        
        res[0][0] = obstacleGrid[0][0] == 1 ? 0:1; //error
        
        for(int i = 1; i < h; i++){
            res[i][0] = obstacleGrid[i][0] == 1 ? 0:res[i-1][0];
        }
        for(int i = 1; i < w; i++){
            res[0][i] = obstacleGrid[0][i] == 1 ? 0:res[0][i-1];
        }
        for(int i = 1; i < h; i++){
            for(int j = 1; j < w; j++){
                res[i][j] = obstacleGrid[i][j] == 1 ? 0:res[i-1][j] + res[i][j-1];
            }
        }
        return res[h-1][w-1];
    }
}

对应的本题也有像Unique Paths一般的降维存储历史信息的方法。

Note: 更新时这里j是从0开始与Unique Paths不同,还有用res[j-1]前要确保j>0.

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        //Method 2
        if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length ==0){
            return 0;
        }
        int h = obstacleGrid.length;
        int w = obstacleGrid[0].length;
        int [] res = new int[w];
        res[0] = obstacleGrid[0][0] == 1 ? 0 : 1;
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){     //error
                if(obstacleGrid[i][j] == 1){
                    res[j] = 0;
                }else{
                    if(j>0){                //error
                        res[j] += res[j-1];
                    }
                }
                
            }
        }
        return res[w-1];
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值