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.
题目描述:一个机器人从m*n网格的左上角走到右下角,每次只能向下或者向右移动一格,求它总共有多少种不同的走法。
思路:典型的动态规划问题,设path[i][j]为机器人从(0,0)走到(i,j)的走法总数,则有如下递推关系式:
path[i][j] = path[i-1][j]+path[i][j-1]
算法的时间复杂度为:O(m*n),优化内存的空间复杂度为O(min(m,n)),代码如下:
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> path(n, 1);
for(int i = 1; i < m; ++i)
for(int j = 1; j < n; ++j)
path[j] = path[j] + path[j-1];
return path[n-1];
}
};
该题还可以看做是一个组合问题,显然总共需要走m+n-2步,其中向下m-1步,向右n-1步,因此使用数学上的组合问题求解算法同样可以解决。
该题的扩展,Unique Paths II,在上题的基础上加了一些限制,也就是网格中设置了一些障碍,这些障碍不能直接跨过,同样求机器人走法的总数。
思路:同样采用动态规划,并且和上题的思路相近,此时的递推关系式如下:
path[i][j] = obstacleGrid[i][j] ? 0 : (path[i-1][j]+path[i][j-1]),也就是如果(i,j)处是障碍,那么path[i][j]=0。算法的时间复杂度为:O(m*n),优化内存的空间复杂度为O(min(m,n)),代码如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int row = obstacleGrid.size();
int col = obstacleGrid[0].size();
int i, j;
vector<int> path(col);
path[0] = 1;
for(i = 0; i < row; ++i)
for(j = 0; j < col; ++j)
if(obstacleGrid[i][j] == 1)
path[j] = 0;
else
path[j] += path[j-1];
return path[col-1];
}
};