类似的题:leetcode62.不同路径(中等) https://blog.csdn.net/zhangjiaji111/article/details/121802934
思路:dp dp[i][j]表示[0][0]到[i][j]的路径数,这样能滚动数组优化 转移方程:dp[i][j]=dp[i-1][j]+dp[i][j-1] 边界:dp[0][0] = (obstacleGrid[0][j] == 0); dp[0][1…m-1]初始化从左边得到
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int n = obstacleGrid.size(), m = obstacleGrid[0].size();
vector<int> dp(m);
dp[0] = (obstacleGrid[0][0] == 0);
if (dp[0] == 0) return 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (obstacleGrid[i][j] == 1) {
dp[j] = 0;
continue;
}
if (j - 1 >= 0) dp[j] += dp[j - 1];
}
}
return dp[m - 1];
}
};
优化:[0][0]为1时直接return 0
题意容易出现的误解: 当[n-1][m-1]为1时,return 0表示不能到达
|