【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,表示从此位置不存在到终点的有效路径。

代码:

 class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[].size();
vector<int> col (n, ); col[n-] = obstacleGrid[m-][n-] == ? : ;
for (int i = m - ; i >= ; --i) {
col[n-] = obstacleGrid[i][n-] == ? : col[n-];
for (int j = n - ; j >= ; --j) {
col[j] = obstacleGrid[i][j] == ? : col[j] + col[j+];
}
} return col[];
}
};

注:

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

上一篇:Intellj IDEA 启动参数调优


下一篇:Log4Net指南