Unique Paths(62,63)
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
思路:
这是一个dp问题。
从最开始,rebort只能向下或者向右。我们假设到达point(i,j)的路径数被设置为p(i,j),那么状态方程:P[i][j] = P[i - 1][j] + P[i][j - 1]
.
The boundary conditions of the above equation occur at the leftmost column (P[i][j - 1]
does not exist) and the uppermost row (P[i - 1][j]
does not exist). These conditions can be handled by initialization (pre-processing) --- initialize P[0][j] = 1, P[i][0] = 1
for all valid i, j
. Note the initial value is 1
instead of 0
!
public class Solution {
public int uniquePaths(int m, int n) {
int[][] map= new int[m][n];
for(int i = 0; i<m;i++){
map[i][0] = 1;
}
for(int j= 0;j<n;j++){
map[0][j]=1;
}
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
map[i][j]=map[i-1][j]+map[i][j-1];
}
}
return map[m-1][n-1];
}
}
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.
总的思路和第一道类似,也是一个dp问题,公式还是:P[i][j] = P[i - 1][j] + P[i][j - 1]
.现在有一个问题就是,如果(i,j)这个点是障碍物,那么到达(i,j)的路径要设置为0.因为不可达。如果不为0,那么:P[i][j] = P[i - 1][j] + P[i][j - 1]
.
剩下的就是初始条件的设定。如果(0,0)为障碍物,那么直接p(0,0)为0不可达。
然后利用P[i][j] = P[i - 1][j] + P[i][j - 1]
. 初始化p(m,0)和p(0,n)
public class Solution {
// public int uniquePathsWithObstacles(int[][] obstacleGrid) {
// int m = obstacleGrid.length;
// int n = obstacleGrid[0].length;
// obstacleGrid[0][0]^=1;
// for(int i = 1;i<m;i++){
// obstacleGrid[i][0]=(obstacleGrid[i][0]==1)? 0:obstacleGrid[i-1][0];
// }
// for(int j = 1;j<n;j++){
// obstacleGrid[0][j] =(obstacleGrid[0][j]==1)? 0: obstacleGrid[0][j-1];
// }
// for(int i = 1;i<m;i++){
// for(int j =1;j<n;j++){
// obstacleGrid[i][j] =(obstacleGrid[i][j]==1)? 0: obstacleGrid[i-1][j]+obstacleGrid[i][j-1];
// }
// }
// return obstacleGrid[m-1][n-1];
// }
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] map= new int[m][n];
map[0][0]=obstacleGrid[0][0]^1;
for(int i = 1;i<m;i++){
map[i][0]=(obstacleGrid[i][0]==1)? 0:map[i-1][0];
}
for(int j = 1;j<n;j++){
map[0][j] =(obstacleGrid[0][j]==1)? 0: map[0][j-1];
}
for(int i = 1;i<m;i++){
for(int j =1;j<n;j++){
map[i][j] =(obstacleGrid[i][j]==1)? 0: map[i-1][j]+map[i][j-1];
}
}
return map[m-1][n-1];
}
}
总结:dp问题关键是找状态方程。 设置初始条件。剩下的按照题目一次添加额外条件。