提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 一、62.不同路径
- 二、63. 不同路径 II
一、62.不同路径
class Solution {
public:int uniquePaths(int m, int n) {vector<vector<int>> path;path.resize(m, vector<int>(n));for (int i = 0; i < n; i ++) {path[0][i] = 1;}for (int j = 1; j < m; j ++) {path[j][0] = 1;}for (int i = 1; i < n; i ++) {for (int j = 1; j < m; j ++) {path[j][i] = path[j-1][i] + path[j][i-1];}}return path.back().back();}
};
二、63. 不同路径 II
class Solution {
public:int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int m = obstacleGrid.size();int n = obstacleGrid[0].size();if (obstacleGrid[0][0] == 1) return 0;obstacleGrid[0][0] = -1;for (int i = 1; i < m; i ++) {if (obstacleGrid[i-1][0] == 1 || obstacleGrid[i][0] == 1) {obstacleGrid[i][0] = 1;}else {obstacleGrid[i][0] = -1;}}for (int j = 1; j < n; j ++) {if (obstacleGrid[0][j-1] == 1 || obstacleGrid[0][j] == 1) {obstacleGrid[0][j] = 1;}else {obstacleGrid[0][j] = -1;}}for (int i = 1; i < m; i ++) {for (int j = 1; j < n; j ++) {if (obstacleGrid[i][j] == 1) continue;if (obstacleGrid[i][j-1] != 1 && obstacleGrid[i-1][j] != 1) {obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1];}else {obstacleGrid[i][j] = min(obstacleGrid[i-1][j], obstacleGrid[i][j-1]);}}}if (obstacleGrid.back().back() == 1) return 0;return -obstacleGrid.back().back();}
};