• [LeetCode] 63. Unique Paths II


    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

    The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

    Now consider if some obstacles are added to the grids. How many unique paths would there be?

    Example 1:

    Input:
    [
      [0,0,0],
      [0,1,0],
      [0,0,0]
    ]
    Output: 2
    Explanation:
    There is one obstacle in the middle of the 3x3 grid above.
    There are two ways to reach the bottom-right corner:
    1. Right -> Right -> Down -> Down
    2. Down -> Down -> Right -> Right

    不同路径II。题意跟版本一一样,唯一的不同点在于路径上会有障碍物。依然是返回到底有多少不同的路径能从左上角走到右下角。

    思路还是跟版本一一样,做法也是一维DP,唯一的不同点在于遇到障碍物的时候,DP数组里面这个坐标的值要置为0,说明是没有办法从起点走到这个点的。所以res数组初始化的时候,如果res[0]设置成1,扫描的范围需要从i = 0, j = 0开始,而版本一这个地方是从i = 0, j = 1开始的。

    时间O(mn)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
     3         int length = obstacleGrid[0].length;
     4         int[] res = new int[length];
     5         res[0] = 1;
     6         for (int i = 0; i < obstacleGrid.length; i++) {
     7             for (int j = 0; j < obstacleGrid[0].length; j++) {
     8                 if (obstacleGrid[i][j] == 1) {
     9                     res[j] = 0;
    10                 } else if (j > 0) {
    11                     res[j] += res[j - 1];
    12                 }
    13             }
    14         }
    15         return res[length - 1];
    16     }
    17 }

    JavaScript实现

     1 /**
     2  * @param {number[][]} obstacleGrid
     3  * @return {number}
     4  */
     5 var uniquePathsWithObstacles = function (obstacleGrid) {
     6     let len = obstacleGrid[0].length;
     7     let res = new Array(len).fill(0);
     8     res[0] = 1;
     9     for (let i = 0; i < obstacleGrid.length; i++) {
    10         for (let j = 0; j < obstacleGrid[0].length; j++) {
    11             if (obstacleGrid[i][j] == 1) {
    12                 res[j] = 0;
    13             } else if (j > 0) {
    14                 res[j] += res[j - 1];
    15             }
    16         }
    17     }
    18     return res[len - 1];
    19 };

    相关题目

    62. Unique Paths

    63. Unique Paths II

    64. Minimum Path Sum

    LeetCode 题目总结

  • 相关阅读:
    xhr1.0和xhr2.0的区别
    Java10-堆和栈
    Java09-函数
    Java08-函数
    java基础7-流程控制3
    Java基础-流程控制2
    Java基础—流程控制1
    breadcrumbs面包屑是啥?
    Font test 字体大小测试用JS代码实现
    数据库密码要BS64才能登录
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12551431.html
Copyright © 2020-2023  润新知