[LeetCode]Unique Paths II

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


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[n];
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];
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6