62. Unique Paths:
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网格的左上角,它只能向右或者向下走,问从左上角地起点到右下角地终点一共有多少条相异的路线。
实际上可以将它看作一个排列组合问题,设R表示向右走,D表示向下走,那么题目就可以转化为,在n-1个R中插入m-1个D,一共有多少种结果。利用排列组合公式,得结果res为(此时设m<n):
1. m > 1时, res = n(n+1)(n+2)……(n+m-2) / (m - 1)!
2. m = 1时, res = 1
n<m时,只需将上述式子中的m和n互换。
代码如下,乘除法同时进行的原因是防止溢出。【时间复杂度为O(min(m, n))】
class Solution {
public:
int uniquePaths(int m, int n) {
long long res = 1;
int maxi = max(m, n);
int mini = min(m, n) - 1;
for (int i = 0; i < mini; i++){
res *= (maxi + i);
res /= (i + 1);
}
return res;
}
};
63. 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.
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.
这题是基于上一题进行扩展而来,在上一题的基础上,添加了障碍物,这样排列组合的方法就不再适用,但因为机器人只能向右或向下走,那么就不存在回头路,用动态规划方法即可解题。
设res[i][j]表示从起点(1, 1)到(i, j),相异路径的数量,因为机器人只能往右或往下走,那么状态转移方程为:
res[i][j] = res[i - 1][j] + res[i][j - 1]
即每个格子的res值等于其上面和左边格子res值的和。
代码如下,首先在第一行上面和第一列左边添加了res值为0的边界,方便后续编程;然后按从左到右,从上到下对格子进行遍历,对那些不是障碍物的格子进行上述状态转移计算;最终返回res[m][n]。【时间复杂度为O(m * n)】
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<int>> res(m + 1, vector<int>(n + 1, 0));
if (obstacleGrid[0][0] == 0) res[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] == 0) {
res[i][j] = res[i - 1][j] + res[i][j - 1];
}
}
}
return res[m][n];
}
};