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?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3 Output: 28
这一题很简单,思路就是设立一个长宽一样的res数组,先初始化第一行和第一列,然后数组中的每个数字等于前面一个和上面一个之和。
class Solution {
public int uniquePaths(int m, int n) {
int [][]res=new int[n][m];
for(int i=0;i<m;i++)
res[0][i]=1;
for(int i=0;i<n;i++)
res[i][0]=1;
for(int i=1;i<n;i++)
for(int j=1;j<m;j++)
{
res[i][j]=res[i-1][j]+res[i][j-1];
}
return res[n-1][m-1];
}
}
下一题设置了障碍如下
Example 1:
Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right与上题的基本思路类似,就是加了一个判断,如果原数组不通,则将对应的res数组值置0,需要注意的是,在初始化的时候如果遇到一个障碍,那后面的数组元素就都为0了。
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m=obstacleGrid.length;
int n=obstacleGrid[0].length;
int [][]res=new int[m][n];
for(int i=0;i<n;i++)
{
if(obstacleGrid[0][i]==1)
{
for(int j=i;j<n;j++)
{
res[0][j]=0;
}
break;
}
else
res[0][i]=1;
}
for(int i=0;i<m;i++)
{
if(obstacleGrid[i][0]==1)
{
for(int j=i;j<m;j++)
{
res[j][0]=0;
}
break;
}
else
res[i][0]=1;
}
for(int i =1;i<m;i++)
for(int j=1;j<n;j++)
{
if(obstacleGrid[i][j]==1)
res[i][j]=0;
else
res[i][j]=res[i-1][j]+res[i][j-1];
}
return res[m-1][n-1];
}
}
我的做法虽然易懂但是看着很不舒服,因为有点长,我看到一位网友的做法很巧妙,也贴在下面,他只用了一维数组而且很简洁,思路大体一致但是需要读者仔细想想才能想通他的精髓。
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int width = obstacleGrid[0].length;
int[] dp = new int[width];
dp[0] = 1;
for (int[] row : obstacleGrid) {
for (int j = 0; j < width; j++) {
if (row[j] == 1)
dp[j] = 0;
else if (j > 0)
dp[j] += dp[j - 1];
}
}
return dp[width - 1];
}
真的很厉害。