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

[LeetCode]Unique Paths II

2016-10-31 19:43 337 查看
Question

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.

本题难度Medium。

一维数组

【复杂度】

时间 O(N^2) 空间 O(N)

【思路】

与Unique Paths的一维数组法一样,只不过多了一个障碍,因此对于
j!=0
dp[j]
赋值:

dp[j]=(obstacleGrid[i][j]==1)?0:dp[j]+dp[j-1];


但是要注意的情况是
dp[0]
的赋值,比如:

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


第二行第一列的值为1,那么不仅它的本行
dp[0]=0
,而且对于第三行第一列
dp[0]=0
。所以在此,对于
dp[0]
值的赋值为:

dp[0]=(dp[0]==0)?0:(obstacleGrid[i][0]==1?0:1);


【代码】

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