题目描述
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.
思路:
| 1 | 1 | 1 |
| 1 | 2 | 3 |
| 1 | 3 | 6 |
| 1 | 4 | 10 |
dp[i][j]矩阵
满足 dp[i][j]=dp[i-1][j]+dp[i][j-1];(i>1&&j>1)
class Solution {
public:
int hash[102][102]={0};
int uniquePaths(int m, int n) {
if(m<=0||n<=0) return -1;
if(m==1||n==1) return 1;
if(hash[m][n]!=0) return hash[m][n];
hash[m][n]=uniquePaths(m,n-1)+uniquePaths(m-1,n);
return hash[m][n];
}
};
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int> >dp(m,vector<int>(n));
dp[0][0]=1;
for(int i=0;i<m;++i)
dp[i][0]=1;
for(int i=0;i<n;++i)
dp[0][i]=1;
for(int i=1;i<m;++i)
for(int j=1;j<n;++j)
dp[i][j]=dp[i-1][j]+dp[i][j-1];
return dp[m-1][n-1];
}
};
拓展题目
题目描述
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 as1and0respectively 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 is2.
Note: m and n will be at most 100.
思路:
| 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 |
obs[i][j]矩阵
| 1 | 1 | 1 | 1 |
| 1 | 0 | 1 | 2 |
| 0 | 0 | 1 | 3 |
| 0 | 0 | 1 | 4 |
dp[i][j]矩阵
如果obs[i][j]==0,那么dp[i][j]=0;
如果obs[i][j]!=0,那么dp[i][j]=dp[i-1][j]+dp[i][j-1];(i>1&&j>1)
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obs) {
int row=obs.size();
int col=obs[0].size();
vector<vector<int> >dp(row,vector<int>(col));
if(obs[0][0]==1) return 0;
dp[0][0]=1;
for(int i=0;i<row;++i)
if(obs[i][0]!=1) dp[i][0]=1;
else break;
for(int i=0;i<col;++i)
if(obs[0][i]!=1) dp[0][i]=1;
else break;
for(int i=1;i<row;++i)
for(int j=1;j<col;++j)
if(obs[i][j]!=1) dp[i][j]=dp[i-1][j]+dp[i][j-1];
else dp[i][j]=0;
return dp[row-1][col-1];
}
};
博客围绕矩阵中机器人路径数量问题展开。首先给出无障碍物时,机器人从左上角到右下角的路径数量求解思路,利用dp[i][j]矩阵,满足dp[i][j]=dp[i - 1][j]+dp[i][j - 1]。接着拓展到有障碍物的情况,根据obs[i][j]矩阵判断,若obs[i][j]=0则dp[i][j]=0,否则按上述公式计算。
5398

被折叠的 条评论
为什么被折叠?



