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

Leetcode63. Unique Paths II

2016-07-04 09:44 483 查看
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.

这个题是62题的升级版,方法和62题一样,采用动态规划。只是当我们遇到障碍物的格子的时候要将其赋值0,,就行了。

public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid.length==0){
return 0;
}
int m =obstacleGrid.length;
int n = obstacleGrid[0].length;
if(n==0){
return 0;
}

if(obstacleGrid[0][0]==1){
return 0;
}

int[][] stepsGrid = new int[m]
;
for(int i=0; i< m ;i++){
if(obstacleGrid[i][0]==1){
break;
}
stepsGrid[i][0] =1;
}

for(int i=0; i<n; i++){
if(obstacleGrid[0][i]==1){
break;
}
stepsGrid[0][i] =1;
}

for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
if(obstacleGrid[i][j]==1){
stepsGrid[i][j]=0;
}else{
stepsGrid[i][j]= stepsGrid[i-1][j]+stepsGrid[i][j-1];
}
}
}

return stepsGrid[m-1][n-1];

}
}

时间复杂度O(m*n),空间复杂度也是O(m*n), 论坛上有空间复杂度为O(1) 的,思路相同,只是在输入数组上修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode