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?
题目就是找m * n方格从左上方到右下方的有多少种不同的路径,开始用组合数学做,就是C(m-1)_(m+n-2),很好写,但是由于分子分母乘的时候太大,会出现溢出的情况,所以WA。
后来就转换成DP,其实这是一个比较标准的DP问题。状态就是当前坐标下有几种路径,即d(i,j)。转移方程也比较好想:d(i,j)=d(i,j-1)+d(i+1,j)。
所以建立一个m*n的数组,把每个路径数都存到数组里面,这样只需要求d(m,n)就行了。
注意,要把第1行和第1列先进行初始化,都变成1,表示一直往右走或者一直往下走。另外,还考虑m或者n为0的情况(不晓得有没有用例,边界条件直接加上了)。
public int uniquePaths(int m, int n) {
if(m == 0 || n == 0) return 0;
int[][] array = new int[m][n];
array[0][0] = 1;
for(int i = 1;i < m;i++){
array[i][0] = 1;
}
for(int i = 1;i < n;i++){
array[0][i] = 1;
}
for(int i = 1;i < m;i++){
for(int j = 1;j < n;j++){
array[i][j] = array[i - 1][j] + array[i][j - 1];
}
}
return array[m - 1][n - 1];
}
61 / 61 test cases passed.
Status: Accepted
Runtime: 212 ms
接下来上Unique Paths II
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.
也就是说,有一个障碍物数组加进来,标1的格子是过不去的。其实跟I一样,用动态规划生成表,只不过在循环的时候加入对障碍物的判断,如果有障碍物的话,表中填0,表示这个格子有0条路径,否则还是用之前的传递函数。
这里注意最上角的位置不能通过计算,应该通过赋值得到。
int[][] array;
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
array = new int[m][n];
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(obstacleGrid[i][j] == 1){
array[i][j] = 0;
}
else if(i == 0 && j == 0){
array[i][j] = 1;
}
else{
array[i][j] = d(i - 1,j) + d(i, j - 1);
}
}
}
return array[m - 1][n - 1];
}
public int d(int i, int j){
if(i >= 0 && j >= 0){
return array[i][j];
}
else{
return 0;
}
}
43 / 43 test cases passed.
Status: Accepted
Runtime: 340 ms