题目:
代码(首刷自解 2024年2月20日):
初始化时注意若有阻碍,则后面都为0
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
/*dp数组表示路径条数*/
vector<vector<int>> dp(m, vector<int>(n, 0));
/*初始化*/
for (int i = 0; i < m && obstacleGrid[i][0] != 1; ++i) dp[i][0] = 1;
for (int i = 0; i < n && obstacleGrid[0][i] != 1; ++i) dp[0][i] = 1;
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (obstacleGrid[i][j] == 1) {
dp[i][j] = 0;
cout<<"!dp["<<i<<"]["<<j<<"] = "<<dp[i][j]<<" ";
} else {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];//递推公式
cout<<"dp["<<i<<"]["<<j<<"] = "<<dp[i][j]<<" ";
}
}
cout<<endl;
}
return dp[m - 1][n - 1];
}
};
代码(二刷自解2024年6月19日 bugfree go)
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
// dp[i][j] 表示到第i行第j列有多少种方法,如果obstacleGrid[i][j] = 1,则对应的dp[i][j] = 0
m, n := len(obstacleGrid), len(obstacleGrid[0])
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
}
for i := 0; i < m && obstacleGrid[i][0] != 1; i++ {
dp[i][0] = 1
}
for j := 0; j < n && obstacleGrid[0][j] != 1; j++ {
dp[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++{
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
if obstacleGrid[i][j] == 1 {
dp[i][j] = 0
}
}
}
return dp[m - 1][n - 1]
}