1.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?
在一个长宽不大于100个格子的棋盘上,机器人占据棋盘左上角的一个格子,每次机器人只能向左或向下走一格,问有多少种走法可以走到右下角的格子。
1.一开始想到的想法是采用递归回溯的思想,但是超时了。
class Solution {
public:
int uniquePaths(int m, int n) {
if(m==1||n==1)
return 1;
else
return uniquePaths(m,n-1)+uniquePaths(m-1,n);
}
};
2.后来想到可以用二维数组来代表棋盘,二维数组上的每一个元素代表走到棋盘相应格子的走法总数,uniquePaths(m,n)<->rst[m-1[n-1];
采用动态规划的思想:rst[i][j]=rst[i-1][j]+rst[i][j-1];
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> rst(m,vector<int>(n,1));
for(int i=1;i<m;i++)
for(int j=1;j<n;j++)
rst[i][j]=rst[i-1][j]+rst[i][j-1];
return rst[m-1][n-1];
}
};
2.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.
和上题的区别在于,棋盘上存在障碍,机器人不能走到有障碍的格子上,问有多少种走法。在棋盘上,1表示有障碍。
采用的思想和上题差不多,只要加个判断就可以了。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m=obstacleGrid.size();
if(m==0)
return 0;
int n=obstacleGrid[0].size();
vector<vector<int>> rst(m,vector<int>(n,1));
int i;
for(i=0;i<n;i++) //第一行的障碍
if(obstacleGrid[0][i]==1)
break;
for(int j=i;j<n;j++)
rst[0][j]=0;
for(i=0;i<m;i++) //第一列的障碍
if(obstacleGrid[i][0]==1)
break;
for(int j=i;j<m;j++)
rst[j][0]=0;
for(i=1;i<m;i++)
for(int j=1;j<n;j++)
if(obstacleGrid[i][j]==1)
rst[i][j]=0;
else
rst[i][j]=rst[i-1][j]+rst[i][j-1];
return rst[m-1][n-1];
}
};