题目

动态规划
public class Main {
public static void main(String[] args) {
Main main = new Main()
main.uniquePathsWithObstacles(new int [][] {{0, 1}, {0, 0}})
}
int m
int n
int [][] dpTable
int [][] obstacleGrid
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
this.m = obstacleGrid.length
this.n = obstacleGrid[0].length
this.obstacleGrid = obstacleGrid
dpTable = new int[m][n]
// 因为只能向右和向下 因此到达某个格子的路径是由它左边的格子和上边的格子走一步得到
// 即dp[i][j] = dp[i + 1][j] + dp[i][j - 1]
// 从底向上计算
for(int i = m - 1
for (int j = 0
dpTable[i][j] = dp(i, j)
}
}
return dpTable[0][n - 1]
}
public int dp(int row, int col) {
if (row >= m || col < 0) {
return 0
}
if (obstacleGrid[m - row - 1][col] == 1) {
return 0
}
if (row == m - 1 && col == 0) {
// 返回到左上
return 1
}
if (dpTable[row][col] != 0) {
return dpTable[row][col]
}
return dp(row + 1, col) + dp(row, col - 1)
}
}
基本思路
- 在不同的路径1的基础上, 新增了一个限制条件, 遇到死路的时候, 返回0