【Leetcode】【Medium】Unique Paths II

Follow up for "Unique Paths":

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

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.

解题思路:

请参见Unique Paths I 的思路,对于Unique Paths II 我们依然希望使用o(n)的额外空间和o(m+n)的时间复杂度;

Unique Paths II中grid[i][n-1]和grid[i-1][n-1]不再总是相等,即格子中最右侧一列每一格存在的路径条数可能为1或0;

因此,为了继续使用Unique Paths I中数组迭代的技巧,需要每次迭代前计算新一轮的grid[i][n-1]值,这样才能继续计算grid[i][0]~grid[i][n-2]的值,从而完成此次迭代;

如果原始格子内为1,则对应此位值置0,表示从此位置不存在到终点的有效路径。

代码:

 1 class Solution {
 2 public:
 3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
 4         int m = obstacleGrid.size();
 5         int n = obstacleGrid[0].size();
 6         vector<int> col (n, 0);
 7         
 8         col[n-1] = obstacleGrid[m-1][n-1] == 1 ? 0 : 1;
 9         for (int i = m - 1; i >= 0; --i) {
10             col[n-1] = obstacleGrid[i][n-1] == 1 ? 0 : col[n-1];
11             for (int j = n - 2; j >= 0; --j) {
12                 col[j] = obstacleGrid[i][j] == 1 ? 0 : col[j] + col[j+1];
13             }
14         }
15         
16         return col[0];
17     }
18 };

注:

养成好习惯,除非特殊说明,不要在原始入参上修改,尤其是入参是地址形式。

原文地址:https://www.cnblogs.com/huxiao-tee/p/4467875.html