您的位置:首页 > 产品设计 > UI/UE

62. Unique Paths && 63. Unique Paths II

2016-01-13 18:19 501 查看
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的各自转化为m*n的矩阵,对于矩阵中(i,j),机器人只能从上或者左边到达,所以path个数为

path[i][j] = path[i][j-1]+path[i-1][j];

边界条件:对于最上面的一行和最左面一列,只能由上/左到达,path = 1

动态规划问题

public class Solution {
public int uniquePaths(int m, int n) {
if (m == 0 || n==0 ) return 0;
if (m == 1 || n == 1) return 1;
int[][] path = new int[m]
;
for (int i = 0; i < m; i++) {
path[i][0] = 1;
}
for (int j = 0; j < n; j++) {
path[0][j] = 1;
}

for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
path[i][j] = path[i-1][j]+path[i][j-1];
}
}
return path[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.

和上题思路相同,只需要加一个判断条件,即如果当前位置有障碍,当前位置的path = 0

public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0) return 0;
int m = obstacleGrid.length , n = obstacleGrid[0].length;
if (m == 0 || n==0 ) return 0;
if(obstacleGrid[m-1][n-1] == 1 || obstacleGrid[0][0] == 1) return 0;

if (m == 1 || n == 1) return 1;
int[][] path = new int[m+1][n+1];
path[1][1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if(i == 1 && j == 1) continue;
if (obstacleGrid[i-1][j-1] ==1 ) {
path[i][j] = 0;
}
else {
path[i][j] = path[i-1][j]+path[i][j-1];
}

}
}
return path[m]
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: