题目描述
解题思路
相比62.不同路径II, 主要是多了障碍物地判断,设\(obstacleGrid[i][j] = 0\),则\(dp_{{i}{j}} = 0\),其余递推关系相同。
注意for
循环遍历地过程中的条件判断。当i = 0
或j = 0
,dp[i][j] = dp[i][j - 1]
或dp[i][j] = dp[i - 1][j]
。
dp[0][0]
= 0。
代码
#include <vector>
using std::vector;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
if (obstacleGrid[i][j] == 1)
dp[i][j] = 0;
else
dp[i][j] = 1;
} else {
if (obstacleGrid[i][j] == 1)
dp[i][j] = 0;
else {
if (i == 0)
dp[i][j] = dp[i][j - 1];
else if (j == 0)
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
}
return dp[m - 1][n - 1];
}
};
标签:vector,paths,obstacleGrid,int,else,ii,63,II,dp
From: https://www.cnblogs.com/zwyyy456/p/16755941.html