leetcode 63. Unique Paths II-唯一路径|动态规划

原文链接:Unique Paths II

【思路】

与  leetcode 62. Unique Paths-唯一路径|动态规划不同的是

这里给机器人增加了障碍物,需要在递推式res[i][j]=res[i-1][j]+res[i][j-1]之前增加一个判断,如果则res[i][j]=0,则res[i][j] = 0:

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int[][] pathCount = new int[obstacleGrid.length][obstacleGrid[0].length];
        for (int i = 0; i < obstacleGrid.length && obstacleGrid[i][0] != 1; i++)
            pathCount[i][0] = 1;
        for (int j = 0; j < obstacleGrid[0].length && obstacleGrid[0][j] != 1; j++)
            pathCount[0][j] = 1;
        for (int i = 1; i < obstacleGrid.length; i++)
            for (int j = 1; j < obstacleGrid[0].length; j++)
                if (obstacleGrid[i][j] == 1) pathCount[i][j] = 0;
                else pathCount[i][j] = pathCount[i - 1][j] + pathCount[i][j - 1];
        return pathCount[obstacleGrid.length - 1][obstacleGrid[0].length - 1];
    }

43 / 43  test cases passed. Runtime: 1 ms  Your runtime beats 17.74% of javasubmissions.

【优化】

这里同样可以将二维数组优化为一维数组。pathCount[i]存放的是矩阵m × n矩阵,m行i列的走法数:

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int[] pathCount = new int[obstacleGrid[0].length];
        pathCount[0] = 1;
        for (int i = 0; i < obstacleGrid.length; i++)
            for (int j = 0; j < obstacleGrid[0].length; j++)
                if (obstacleGrid[i][j] == 1) pathCount[j] = 0;
                else if (j > 0) pathCount[j] += pathCount[j - 1];
        return pathCount[obstacleGrid[0].length - 1];
    }

43 / 43 test cases passed. Runtime: 1 ms  Your runtime beats 17.74% of javasubmissions.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值