您的位置:首页 > 产品设计 > UI/UE

【Leetcode】【Medium】Unique Paths II

2015-04-30 00:45 435 查看
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[0].size();
vector<int> col (n, 0);

col[n-1] = obstacleGrid[m-1][n-1] == 1 ? 0 : 1;
for (int i = m - 1; i >= 0; --i) {
col[n-1] = obstacleGrid[i][n-1] == 1 ? 0 : col[n-1];
for (int j = n - 2; j >= 0; --j) {
col[j] = obstacleGrid[i][j] == 1 ? 0 : col[j] + col[j+1];
}
}

return col[0];
}
};


注:

养成好习惯,除非特殊说明,不要在原始入参上修改,尤其是入参是地址形式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: