classSolution{ // top-down publicintuniquePathsWithObstacles(int[][] obstacleGrid){ // without padding int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] dp = newint[m][n];
// initialize the base cases. for (int i = 0; i < m; i++) { Arrays.fill(dp[i], -1); }
int value = 1; for (int j = 0; j < n; j++) { if (obstacleGrid[0][j] == 1) { value = 0; } dp[0][j] = value; } value = 1; for (int i = 0; i < m; i++) { if (obstacleGrid[i][0] == 1) { value = 0; } dp[i][0] = value; }
return helper(obstacleGrid, dp, m - 1, n - 1);
}
privateinthelper(int[][] grid, int[][] dp, int m, int n){ if (m < 0 || n < 0) { return0; } if (grid[m][n] == 1) { return0; } if (dp[m][n] != -1) { return dp[m][n]; }
dp[m][n] = 0; dp[m][n] += helper(grid, dp, m - 1, n); dp[m][n] += helper(grid, dp, m, n - 1);
classSolution{ // bottom-up publicintuniquePaths(int m, int n){ int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] dp = newint[m][n];
// initialize the base cases. for (int i = 0; i < m; i++) { Arrays.fill(dp[i], -1); }
int value = 1; for (int j = 0; j < n; j++) { if (obstacleGrid[0][j] == 1) { value = 0; } dp[0][j] = value; } value = 1; for (int i = 0; i < m; i++) { if (obstacleGrid[i][0] == 1) { value = 0; } dp[i][0] = value; }
for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (grid[i][j] == 1) { dp[i][j] = 0; continue; } dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } }