62. Unique Paths
- Total Accepted: 132181
- Total Submissions: 328812
- Difficulty: Medium
- Contributor: LeetCode
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 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Subscribe to see which companies asked this question.
思路:
建立一个m×n、值均为1的数组,从第二行、第二列开始,每个位置的元素的值为该元素的上方和左方的值之和,这样即是将向下行或向右行的路径都记录到所走到的位置上。
代码:
class Solution {
public:
int uniquePaths(int m, int n) {
vector
> p(m, vector
(n, 1));
for(int i = 1; i < m; i ++){
for(int j = 1; j < n; j ++){
p[i][j] = p[i - 1][j] + p[i][j - 1];
}
}
return p[m - 1][n - 1];
}
};
63. Unique Paths II
- Total Accepted: 98066
- Total Submissions: 313014
- Difficulty: Medium
- Contributor: LeetCode
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.
Subscribe to see which companies asked this question.
思路:
建立一个(m+1)×(n+1)、值均为0的数组p,其中p[0][1] = 1,根据数组obstacleGrid行为i、列为j的值,若为0(即可通行)则赋值p[i][j]为1,若为1则赋值为0。再从数组p的第二行、第二列开始,若p[i][j]的值为1,则将该位置的值赋为p[i-1][j]和p[i][j-1]的和。
代码:
class Solution {
public:
int uniquePathsWithObstacles(vector
>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector
> p(m + 1, vector
(n + 1, 0)); p[0][1] = 1; for(int i = 0; i < m; i ++){ for(int j = 0; j < n; j ++){ if(obstacleGrid[i][j] == 1) p[i + 1][j + 1] = 0; else p[i + 1][j + 1] = 1; } } for(int i = 1; i <= m; i ++){ for(int j = 1; j <= n; j ++){ if(p[i][j] == 1) p[i][j] = p[i - 1][j] + p[i][j - 1]; } } return p[m][n]; } };