public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid.length == 0 || obstacleGrid[0].length == 0 || obstacleGrid[0][0] == 0) return 0;
int n = obstacleGrid[0].length;
int[] dp = new int[n];
dp[0] = 1;
for (int[] row : obstacleGrid) {
for (int i = 0; i < n; i++) {
if (row[i] == 1) dp[i] = 0;
else if (i > 0) dp[i] += dp[i-1];
}
}
return dp[n-1];
}
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid.length == 0 || obstacleGrid[0].length == 0 || obstacleGrid[0][0] == 1) return 0;
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
obstacleGrid[0][0] ^= 1;
for (int i = 1; i < cols; i++)
obstacleGrid[0][i] = obstacleGrid[0][i] == 1 ? 0 : obstacleGrid[0][i-1];
for (int i = 1; i < rows; i++)
obstacleGrid[i][0] = obstacleGrid[i][0] == 1 ? 0 : obstacleGrid[i-1][0];
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (obstacleGrid[i][j] == 1)
obstacleGrid[i][j] = 0;
else
obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1];
}
}
return obstacleGrid[rows-1][cols-1];
}
63. Unique Paths II
最新推荐文章于 2020-07-06 10:19:42 发布