leetcode之Unique Paths 和Unique Paths II

来源:互联网 发布:淘宝卖视频教程 编辑:程序博客网 时间:2024/05/07 06:42

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?

这道题就是典型的动态规划题,到达当前节点的paths由其左边和上边的两个元素决定,即动态方程为:path[i][j] = path[i-1][j] + path[i][j-1];所以需要首先对第一列和第一行置1,然后依次遍历剩余的元素,最后返回path[m-1][n-1]的值即可。

class Solution {public:    int uniquePaths(int m, int n) {         if(m == 0 || n == 0)return 0;int **path = new int*[m];for(int i = 0; i < m; i ++){path[i] = new int[n];path[i][0] = 1;}for(int j = 1; 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];    }};

Unique pathsII 的原题如下:

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.

其实在做出第一道题的基础上,这道题也就相对容易了许多,仍采用动态规划,与第一题相比有以下不同:在给第一列和第一行赋初值的时候与第一题有所不同,当在第一行或第一列遇到障碍时,其后的元素都是不可达的,所以应该置0。另外,在遍历的过程中,若当前元素为1,则直接置0,只有在当前元素没有障碍的情况下才利用动态方程求解。最后,编程时注意边界条件,就因为边界导致前几次提交都是WA,我的代码中对边界的控制可能有冗余,但这应该不影响算法的效率。

class Solution {public:    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {int m = obstacleGrid.size();if(m == 0)return 0;int n = obstacleGrid[0].size();if(n == 0)return 0;if(obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][ n - 1] == 1)//起点和终点如果有障碍肯定无法到达return 0;if(m == 1 && n == 1)//只有一个且没有障碍能够到达return 1;int flag = 1;int i = 0;for(i = 1 ;i < m; i++){ //如果第一列没有障碍,将第一列置1,否则将第一列1之后的元素置0if(obstacleGrid[i][0] == 1){flag = 0;break;}if(obstacleGrid[i][0] == 0){obstacleGrid[i][0] = 1;}}while(i < m){obstacleGrid[i++][0] = flag;}if(n == 1)return flag;flag = 1;int j = 0;for(j = 1; j < n; j++){  //如果第一行没有障碍,将第一行置1,否则将第一行1之后的元素置-1if(obstacleGrid[0][j] == 1){    flag = 0;break;}if(obstacleGrid[0][j] == 0)obstacleGrid[0][j] = 1;}while(j < n){obstacleGrid[0][j++] = flag;}if(m == 1)return flag;for(int i = 1; i < m; i++){for(int j = 1; j < n; j++){if(obstacleGrid[i][j] == 1)  //如果当前元素为1,则有障碍无法到达置0obstacleGrid[i][j] = 0;elseobstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][ j - 1];}}return obstacleGrid[m - 1][ n - 1];    }};




0 0
原创粉丝点击