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?
Note: m and n will be at most 100.
题目的意思是这样的,给定一个m*n的矩形方格,每次走一格,并且只能向右和向下走,求从左上角到右下角的路径数。
暴力解法对大数组肯定是超时间的,所以考虑动态规划。每次到达当前格路径数为到达左边格路径数加上到达上边格的路径数。
public class Solution {
public int uniquePaths(int m, int n) {
int[][] paths = new int[m][n];
for (int i = 0; i < m; i++) {//左边界
paths[i][0] = 1;
}
for (int i = 0; i < n; i++) {//上边界
paths[0][i] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
paths[i][j] = paths[i-1][j]+paths[i][j-1];
}
}
return paths[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.
在问题二中放置了一些障碍物,1表示有障碍物,0表示可以走,求总共有多少条不重复路径。其实只要把障碍地方的解变为 0 就好。
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rows = obstacleGrid.length;
if (rows < 1) return 0;
int cols = obstacleGrid[0].length;
if (cols < 1) return 0;
if (obstacleGrid[0][0] == 1) return 0;//如果第一个元素就为1,第一个就是障碍物,不用再往下判断了
int[][] paths = new int[rows][cols];
paths[0][0] =1;
for (int i = 1; i < rows; i++) {
if (obstacleGrid[i][0] == 1) {
paths[i][0] = 0;
}
else {
paths[i][0] = paths[i-1][0];
}
}
for (int i = 1; i < cols; i++) {
if (obstacleGrid[0][i] == 1) {
paths[0][i] = 0;
}
else {
paths[0][i] = paths[0][i-1];
}
}
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (obstacleGrid[i][j] == 1) {
paths[i][j] = 0;
}else {
paths[i][j] = paths[i-1][j]+paths[i][j-1];
}
}
}
return paths[rows-1][cols-1];
}
}
也有人优化到一维数组来解决上面这两个问题。我还是先用二维数组这样来解吧,这样好理解一些。首先就是先把左边界和上边界赋值,然后再一步一步算。