1 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?
因为只能向右和向下移动,所以在
int uniquePaths(int m, int n) {
vector<vector<int> > path(m,vector<int>(n,0));
//初始化顶部和左边的格子
for(int i=0;i<m;i++) path[i][0]=1;
for(int j=0;j<n;j++) path[0][j]=1;
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
path[i][j]=path[i-1][j]+path[i][j-1];
}
}
return path[m-1][n-1];
}
利用上一轮的计算结果,可以将二维数组降为一维
int uniquePaths(int m, int n) {
vector<int> path(n,0);
for(int j=0;j<n;j++) path[j]=1;
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
path[j]=path[j]+path[j-1];
}
}
return path[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.
与上一题一样,用
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m=obstacleGrid.size();
int n=obstacleGrid[0].size();
vector<vector<int> > path(m,vector<int>(n,0));
path[0][0]=obstacleGrid[0][0]==1? 0:1;
for(int i=1;i<m;i++) path[i][0]=obstacleGrid[i][0]==1? 0:path[i-1][0];
for(int j=1;j<n;j++) path[0][j]=obstacleGrid[0][j]==1? 0:path[0][j-1];
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
path[i][j]=obstacleGrid[i][j]==1? 0:(path[i-1][j]+path[i][j-1]);
}
}
return path[m-1][n-1];
}
3 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.
与第一题方法相似
int minPathSum(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
vector<vector<int> > path(m,vector<int>(n,0));
path[0][0]=grid[0][0];
for(int i=1;i<m;i++) path[i][0]=path[i-1][0]+grid[i][0];
for(int j=1;j<n;j++) path[0][j]=path[0][j-1]+grid[0][j];
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
path[i][j]=grid[i][j]+min(path[i-1][j],path[i][j-1]);
}
}
return path[m-1][n-1];
}
原文地址:http://blog.csdn.net/zhulong890816/article/details/45932615