您的位置:首页 > 产品设计 > UI/UE

【LeetCode】Unique Paths I && II && Minimum Path Sum

2014-06-18 13:38 519 查看
题目描述:

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?

Note: m and n will be at most 100.
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.

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.

这三道题目都是一个思路,简单的dp思想。

对第一题来说,dp[i][j]=dp[i-1][j]+dp[i][j-1]。

对第二题,公式是一样的,但添加一个条件,当i,j位置为1时dp[i][j]=0。

第三题的话,dp[i][j]=min(dp[i-1][j],dp[i][j-1]) + val[i][j]。

代码:

1、Unique Paths

class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> matrix(m + 1, vector<int>(n + 1, 0));
if (!n || !m)
return 0;
matrix[1][1] = 1;
for (int i = 1; i < m + 1;i++)
for (int j = 1; j < n + 1; j++){
if (i == 1 && j == 1)
continue;
matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1];
}
return matrix[m]
;
}
};


2、Unique Paths II

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
vector<vector<int>> matrix(obstacleGrid.size() + 1, vector<int>(obstacleGrid[0].size() + 1, 0));
if (obstacleGrid[0][0])
return 0;
matrix[1][1] = 1;
for (int i = 1; i < matrix.size(); i++)
for (int j = 1; j < matrix[0].size(); j++){
if (i == 1 && j == 1 || obstacleGrid[i - 1][j - 1])
continue;
matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1];
}
return matrix[matrix.size() - 1][matrix[0].size() - 1];
}
};


3、Minimum Path Sum

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