Unique Paths | & ||

时间:2023-03-08 23:25:47
Unique Paths | & ||

Unique Paths I

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?

分析:

用A[i][j]表示到达点i,j可能的走法。 对于点A[i][j],它可以从上一个格子下来,也可以从左边那个格子过来。所以A[i][j] = A[i-1][j] + A[i][j-1].

 public class Solution {
/**
* @param n, m: positive integer (1 <= n ,m <= 100)
* @return an integer
*/
public int uniquePaths(int m, int n) {
if (n < || m < ) return ;
if (n == || m == ) return ; int[][] paths = new int[m][n]; for (int i = ; i < paths.length; i++) {
for (int j = ; j < paths[].length; j++) {
if (i == || j == ) {
paths[i][j] = ;
} else {
paths[i][j] = paths[i - ][j] + paths[i][j - ];
}
}
}
return paths[m - ][n - ];
}
}

Another solution:

(For clarity, we will solve this part assuming an X+1 by Y+1 grid)

Each path has X+Y steps. Imagine the following paths:

X X Y Y X (we move right on the first 2 steps, then down on the next 2, then right  for the last step)

X Y X Y X (we move right, then down, then right, then down, then right)

Each path can be fully represented by the moves at which we move right. That is, if I were to ask you which path you took, you could simply say “I moved right on step 3 and 4.” Since you must always move right X times, and you have X + Y total steps, you have to pick X times to move right out of X+Y choices. Thus, there are C(X, X+Y) paths (eg, X+Y choose X).

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.

Example

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.

分析:

原理同上,没有任何区别。

 public class Solution {
/**
* @param obstacleGrid: A list of lists of integers
* @return: An integer
*/
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == || obstacleGrid[].length == ) return ; int m = obstacleGrid.length;
int n = obstacleGrid[].length; int[][] paths = new int[m][n]; for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (obstacleGrid[i][j] == ) {
paths[i][j] = ;
} else if (i == && j == ) {
paths[i][j] = ;
} else if (i == ) {
paths[i][j] = paths[i][j - ];
} else if (j == ) {
paths[i][j] = paths[i - ][j];
} else {
paths[i][j] = paths[i - ][j] + paths[i][j - ];
}
}
}
return paths[m - ][n - ];
}
}