时间复杂度:O(m * n)。
空间复杂度:O(m * n)。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
int dp[m][n];
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (obstacleGrid[i][j] == 1) {
dp[i][j] = 0;
continue;
}
if (i >= 1) {
dp[i][j] += dp[i-1][j];
}
if (j >= 1) {
dp[i][j] += dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
};
时间复杂度:O(m * n)。
空间复杂度:O(n)。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
int dp[n+1];
memset(dp, 0, sizeof(dp));
dp[1] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (obstacleGrid[i][j]) {
dp[j+1] = 0;
continue;
}
dp[j+1] = dp[j+1] + dp[j];
}
}
return dp[n];
}
};