LeetCode 063、不同路径 II
题目
题解
五部曲分析问题,注意递推公式:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
(i, j)如果是障碍的话就应该保持初始状态0
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int row = obstacleGrid.size();
int col = obstacleGrid[0].size();
vector<vector<int>> dp(row, vector<int>(col, 0));
for (int i = 0; i < row && obstacleGrid[i][0] == 0; ++i) dp[i][0] = 1;
for (int j = 0; j < col && obstacleGrid[0][j] == 0; ++j) dp[0][j] = 1;
for (int i = 1; i < row; ++i) { // 注意i从1开始
for (int j = 1; j < col; ++j) { // 同样注意,j从1开始
if (obstacleGrid[i][j] == 0) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[row - 1][col - 1];
}
};