题目:
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.
链接:
4/26/2017
1ms, 19%
跟unique paths差不多,区别是,如果是障碍那么dp为0,并且初始化边界的时候也要注意这个条件。
注意的问题:
1. 判断非法输入
2. 在初始化第一行和第一列的时候就要想到有obstacle,所以要判断是否当前为障碍,以及如果之前一个dp是0,现在的也应该是0
3. 注意typo,不要随便copy & paste,比如第8行开始是obstacleGrid,后面是dp
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; 4 5 int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length]; 6 7 for (int i = 0; i < obstacleGrid.length; i++) { 8 if (obstacleGrid[i][0] == 1 || i > 0 && dp[i - 1][0] == 0) { 9 dp[i][0] = 0;10 } else {11 dp[i][0] = 1;12 }13 }14 for (int i = 0; i < obstacleGrid[0].length; i++) {15 if (obstacleGrid[0][i] == 1 || i > 0 && dp[0][i - 1] == 0) {16 dp[0][i] = 0;17 } else {18 dp[0][i] = 1;19 }20 }21 for (int i = 1; i < obstacleGrid.length; i++) {22 for (int j = 1; j < obstacleGrid[0].length; j++) {23 if (obstacleGrid[i][j] == 1) {24 dp[i][j] = 0;25 } else {26 dp[i][j] = dp[i][j - 1] + dp[i - 1][j];27 }28 }29 }30 return dp[obstacleGrid.length - 1][obstacleGrid[0].length - 1];31 32 }33 }
别人的算法
一维DP
1 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 2 int width = obstacleGrid[0].length; 3 int[] dp = new int[width]; 4 dp[0] = 1; 5 for (int[] row : obstacleGrid) { 6 for (int j = 0; j < width; j++) { 7 if (row[j] == 1) 8 dp[j] = 0; 9 else if (j > 0)10 dp[j] += dp[j - 1];11 }12 }13 return dp[width - 1];14 }
更多讨论: