Leetcode-62. Unique Paths and 63. Unique Paths II

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?

题目太简单,典型的动态规划思想,直接贴代码吧!!!

class Solution {
public:
	int uniquePaths(int m, int n) {
		if (m == 0 || n == 0)return 0;
		if (m == 1 || n == 1)return 1;
		vectorvec(n,0);
		vector>tmp;
		for (int i = 0; i < m; i++)tmp.push_back(vec);
		for (int i = 0; i < m; i++)tmp[i][0] = 1;
		for (int i = 0; i < n; i++)tmp[0][i] = 1;
		for (int i = 1; i < m;i++){
			for (int j = 1; j < n;j++){
				tmp[i][j] = tmp[i - 1][j] + tmp[i][j-1];
			}
		}
		return tmp[m-1][n-1];
	}
};

运行结果:

Submission Result: Accepted  More Details 

Next challenges:  (H) Dungeon Game

Share your acceptance!

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.

Note: m and n will be at most 100.

Subscribe to see which companies asked this question

版本2的限制条件为矩阵中右障碍物,但是大体的思想还是一样的。

1.当遇到障碍物时,直接将tmp的值设置为0,并且直接continue跳过去;

2.障碍物时,第一行和第一列不能直接设置成1。因为当障碍物出现在第一行或是第一列时,那么第一行和第一列的后续的格子中的所有值均为0。解答完

毕!!!!

class Solution {
public:
	int uniquePathsWithObstacles(vector>& obstacleGrid) {
		int row = obstacleGrid.size();
		int col = obstacleGrid[0].size();
		if (row == 0 || col == 0)return 0;
		if (obstacleGrid[0][0] == 1)return 0;//入口被堵死
		vectorvec(col, 0);
		vector>tmp;
		for (int i = 0; i < row; i++)tmp.push_back(vec);
		//填表
		tmp[0][0] = 1;
		for (int i = 0; i < row; i++){
			for (int j = 0; j < col; j++){
				if (obstacleGrid[i][j] == 1){
					tmp[i][j] = 0;
					continue;
				}
				tmp[i][j] = max((i>0 ? tmp[i - 1][j] : 0) + (j>0 ? tmp[i][j - 1] : 0), tmp[i][j]);
			}
		}
		return tmp[row-1][col-1];
	}
};
运行结果:

Submission Result: Accepted  More Details 

Next challenges:  (M) Unique Paths

Share your acceptance!



你可能感兴趣的:(leetcode算法)