您的位置:首页 > 其它

LeetCode_62、63、64三题(动态规划)

2018-04-11 05:04 274 查看
LeetCode_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?

解析:就是问从左下角到右下角有多少条路径。这是一题典型的动态规划问题,考虑终点,到终点的前一步有两种:1、终点左边右移一步。2、终点上面下移一步。

再把最左一排和最上面一排初始化为1条路径(很显然)。

具体代码如下:

class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector <int> > a;
a.resize(m);
for(int i = 0;i < m;i++){
a[i].resize(n);
}
for(int i = 0;i < m;i++){
a[i][0] = 1;
}
for(int i = 0;i < n;i++){
a[0][i] = 1;
}
for(int i = 1;i < m;i++){
for(int j = 1;j < n;j++){
a[i][j] = a[i-1][j] + a[i][j-1];
}
}
return a[m-1][n-1];
}
};


LeetCode_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

解析:题意和前一题一模一样,只是在中间加了一些障碍物,即表示不能到达障碍物。则根据前一题,多添加一个判断:前一步为障碍物则不能到达。这里需要注意的是左边界和上边界的1,他们分别下面的和右边的是不能达到的。还有就是终点是1的,路径显然就是

具体代码如下:

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {

vector<vector <int> > a;
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[m-1][n-1] == 1)return 0;
a.resize(m);
for(int i = 0;i < m;i++){
a[i].resize(n,0);
}
for(int i = 0;i < m;i++){
if(obstacleGrid[i][0] == 1){
break;
}
a[i][0] = 1;
}
for(int i = 0;i < n;i++){
if(obstacleGrid[0][i] == 1){
break;
}
a[0][i] = 1;
}
for(int i = 1;i < m;i++){
for(int j = 1;j < n;j++){
if(obstacleGrid[i-1][j] != 1)a[i][j] = a[i-1][j];
if(obstacleGrid[i][j-1] != 1)a[i][j] += a[i][j-1];
}
}
return a[m-1][n-1];
}
};


LeetCode_64. Minimum Path Sum

原题:

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

解析:找到从左下角到右下角的最小和,也是典型的动态规划问题,到达前一步是最小和,则到达下一步也是最小和。

具体代码如下:

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> getmin(m, vector<int>(n,INT_MAX));
if(m == 1 && n == 1)return grid[0][0];
for(int i = 0;i < m;i ++){
for(int j = 0;j < n;j ++){
if(i == 0 && j == 0)getmin[i][j] = grid[i][j];
else if(i > 0 && j == 0)getmin[i][j] = getmin[i-1][j] + grid[i][j];
else if(i == 0 && j > 0)getmin[i][j] = getmin[i][j-1] + grid[i][j];
else getmin[i][j] = min(getmin[i][j-1],getmin[i-1][j]) + grid[i][j];
}
}
return getmin[m-1][n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: