题目: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?
题意:从左上角到右下角的路径数,每次只能向下或向右移。
算法思路:利用动态规划的思维,用一个nxm 的数组memo来存储每个点的路径数,先初始化第一行和第一列的点的路径数为1,然后依次遍历剩余的点,每个点的路径数等于左和上的点的路径和。返回最后一个点的路径数。
参考代码:
//leetcode 62. Unique Paths
public int uniquePaths(int m, int n) {
int[][] memo = new int[n][m];
for(int i=0;i<n;i++)
memo[i][0] = 1;
for(int i=0;i<m;i++)
memo[0][i] = 1;
for(int i=1;i<n;i++){
for(int j=1;j<m;j++){
memo[i][j] = memo[i-1][j] + memo[i][j-1];
}
}
return memo[n-1][m-1];
}
leetcode 63. Unique Paths II
题意:在此基础上,图中的点可能是空的(0表示),也可能是障碍(1表示),有障碍的点是不可到达的,该点的路径数为0。要注意的是先要把第一个点给初始化了,该点的值是0则初始化为1,是1则初始化为0。然后依次初始化第一行和第一列,再遍历剩余的点,若该 点为空,则该点的路径数等于左和上的点的路径和,若该点是障碍,则该 点的路径数为0。返回最后一个点的路径数。
参考代码:
//leetcode 63. Unique Paths II
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length;
if(n==0)
return 0;
int m = obstacleGrid[0].length;
int[][] memo = new int[n][m];
if(obstacleGrid[0][0] == 0)
memo[0][0] = 1;
else
memo[0][0] = 0;
for(int i=1;i<n;i++){
if(obstacleGrid[i][0] == 0)
memo[i][0] = memo[i-1][0];
else
memo[i][0] = 0;
}
for(int i=1;i<m;i++){
if(obstacleGrid[0][i] == 0)
memo[0][i] = memo[0][i-1];
else
memo[0][i] = 0;
}
for(int i=1;i<n;i++){
for(int j=1;j<m;j++){
if(obstacleGrid[i][j] == 0)
memo[i][j] = memo[i-1][j] + memo[i][j-1];
else
memo[i][j] = 0;
}
}
return memo[n-1][m-1];
}