题目描述
思路
这道题并不难,常规的动态规划思路,递推公式也并不难想。
但是贴这题的目的是比较一下题解和我的代码在具体实现上的区别;
代码随想录:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) //如果在起点或终点出现了障碍,直接返回0
return 0;
vector<vector<int>> dp(m, vector<int>(n, 0));
//dp数组的值全部初始化为0,所以不必再给障碍位置的dp赋值为0
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) dp[i][0] = 1;
//当没有遇到障碍时,对边界的dp赋值为1,遇到障碍后直接推出循环,
//这样就很自然地把循环后面的值都设为0了
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) dp[0][j] = 1;
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 1) continue;
//这里,遇到障碍时直接continue跳过,就把这里的dp保留为0了
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};
OK,再看看我的代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(m == 1 || n == 1){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(obstacleGrid[i][j]){
return 0;
}
}
}
return 1;
}
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(obstacleGrid[i][j]){
dp[i][j] = 0;
continue;
}
//if(i == 0 || j == 0){
if(i == 0 && j == 0){
dp[i][j] = 1;
continue;
}
if(i == 0 && j != 0){
dp[i][j] = dp[i][j-1];
continue;
}
if(i != 0 && j == 0){
dp[i][j] = dp[i-1][j];
continue;
}
dp[i][j] = dp[i-1][j] + dp[i][j-1];
//}
}
}
return dp[m-1][n-1];
}
};