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

unique paths II

2015-02-01 15:08 183 查看
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.

网上看到别人写的,1D DP很巧妙, 因为总是往一个方向走,实际上只需要维护一个1D的数组就可以了。 和上面不一样的是需要有一个检查是不是有obstacle,如果有那么设置为0,此路不通,在tbl[j+1]中则认为此为无效。 而在其他的循环中, tb[i][j]则由其他来维护,也就不需要担心=0会抹掉什么。 挺绕的。。。

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


回到2D的规划,因为条件变了,中间有阻隔,上次取巧的设置为1改起来好麻烦,设置0,0为1,然后按照1维来更新通不通, 这个在我看来的好处是处理2x2的数组有用,再就是本来你也少不了需要判断m=1,n=1的时候。 从YU'S coding garden那里直接抄来吧。。。

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();

vector<vector<int> > arr(m,vector<int>(n,0));

if (obstacleGrid[0][0]==1){return 0;}
arr[0][0]=1;
for (int i=1;i<m;i++){
if (obstacleGrid[i][0]!=1){
arr[i][0] = arr[i-1][0];
}
}
for (int i=1;i<n;i++){
if (obstacleGrid[0][i]!=1){
arr[0][i] = arr[0][i-1];
}
}
for (int i=1;i<m;i++){
for(int j=1;j<n;j++){
if (obstacleGrid[i][j]!=1){
arr[i][j] = arr[i][j-1] + arr[i-1][j];
}
}
}
return arr[m-1][n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode