LeetCode: Unique Paths I & II & Minimum Path Sum

Title:

https://leetcode.com/problems/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?

LeetCode: Unique Paths I & II & Minimum Path Sum

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

思路:直观的思路是使用递归,但是会超时

class Solution{
public:
int m;
int n;
int uniquePaths(int m, int n) {
this->m = m;
this->n = n;
int sum = ;
fun(,,sum);
return sum;
}
void fun(int i,int j,int& sum){
if (i == m && j == n)
sum++;
if (i > m || j > n)
return ;
fun(i+,j,sum);
fun(i,j+,sum);
}
};
int uniquePaths(int m,int n){
if (m == || n == )
return ;
return uniquePaths(m-,n)+uniquePaths(m,n-);
}

一般这种递归都可以使用动态规划来解决

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

Unique Path II

https://leetcode.com/problems/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.

开始想直接使用I中的,却没有考虑到边界上有障碍的情况

int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid){
if (obstacleGrid.empty())
return ;
int m = obstacleGrid.size();
int n = obstacleGrid[].size();
if (m < || n < )
return ;
vector<int> result(n);
result[] = ;
for (int i = ; i < m ; i++){
for (int j = ; j < n ; j++){
if (obstacleGrid[i][j] == )
result[j] = ;
else{
if (j > )
result[j] += result[j-];
}
}
}
return result[n-];
}

Minimun-Path-Sum

Title:

https://leetcode.com/problems/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){
if (grid.empty() || grid.size() == )
return ;
int m = grid.size();
int n = grid[].size();
vector<int> v(n,INT_MAX);
v[] = ;
for (int i = ; i < m; i++){
for (int j = ; j < n; j++){
if (j == ){
v[j] = v[j] + grid[i][j];
}else{
v[j] = min(v[j],v[j-]) + grid[i][j];
}
//cout<<v[j]<<" ";
}
//cout<<endl;
}
//cout<<endl;
return v[n-];
}
};
上一篇:LeetCode—Unique Paths


下一篇:期货大赛项目|二,DAL详解