63.Unique Paths II:修订间差异
第3行: | 第3行: | ||
=Solution= | =Solution= | ||
== 2D DP== | == 2D DP== | ||
{{Submission|runtime=1ms|memory= | {{Submission|runtime=1ms|memory=40.02MB|rp=19.16|mp=98.98}} | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
class Solution { | class Solution { |
2023年9月23日 (六) 12:59的版本
Description
Solution
2D DP
Runtime 1ms |
|
Memory 40.02MB |
|
class Solution {
private int[][] grid;
private int rows;
private int cols;
private int[][] dp;
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
this.grid = obstacleGrid;
this.rows = obstacleGrid.length;
this.cols = obstacleGrid[0].length;
this.dp = new int[rows][cols];
for(int[] temp: dp)
Arrays.fill(temp, -1);
for(int i = rows - 1; i >=0; i--) {
for(int j = cols -1; j >= 0; j--) {
if(grid[i][j] == 1)
dp[i][j] = 0; // obstacle
else if( i == rows -1 && j == cols -1)
dp[i][j] = 1; // reach end
else {
int ways = 0;
if(i < rows -1).
ways += dp[i+1][j]; // going down
if(j < cols -1)
ways += dp[i][j+1]; // going right
dp[i][j] = ways;
}
}
}
return dp[0][0];
}
}