不同路径I
思路:定义一个二维的dp数组
1.dp[i][j]表示从(0,0)到(i,j)的路径条数
2.dp[i][j] = dp[i-1][j] + dp[i][j-1];从上一状态得到当前状态方程
两个方向过来当前位置,是两条路径,路径条数,不是步数
3.初始化
dp[i][0] = 1;
dp[0][j] = 1;
4.确定遍历顺序
从上到下 或 从左到右
5.举例推导,尝试带入 3,7,手动打印
class Solution{
public:
int uniquePaths(int m, int n){
vector<vector<int>>dp(m,vector<int>(n,0));
for(int i = 0; i < m; i++)dp[i][0] = 1;
for(int j = 0; j < n; j++)dp[0][j] = 1;
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};
优化:
class Solution{
public:
int uniquePaths(int m, int n){
vector<int> dp(n);
for(int i=0; i < n; i++)dp[i] = 1;
for(int j=1; j < m; j++){
for(int i = 1l i < n; i++){
dp[i] += dp[i-1];
}
}
return dp[n-1];
}
};
不同路径II
思路分析:加入了障碍,标记对应的dp table,保持初始值(0)即可。
1.dp[i][j]表示从(0,0)到(i,j)的不同路径数
2.dp[i][j] = dp[i - 1][j] + dp[i][j -1].
如果(i,j)就是障碍的话,应该保持初始状态(初始状态为0)
if (obstacleGrid[i][j] == 0) { // 当(i, j)没有障碍的时候,再推导dp[i][j]
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
3.初始化
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) dp[i][0] = 1;
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) dp[0][j] = 1;
obs为0时才进行,为1不进行
4.遍历顺序:从左到右,从上到下
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 1) continue;
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
5.打印debug
class Solution{
public:
int uniquePathWithObtacles(vector<vector<int>>&obsracleGrid){
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1)//终点或起点出现障碍
return 0;
vector<vector<int>>dp(m,vector<int>(n,0));
for(int i = 0; i < m && obstacleGrid[i][0] == 0; i++)dp[i][0] = 1;
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;
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};
优化:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if (obstacleGrid[0][0] == 1)
return 0;
vector<int> dp(obstacleGrid[0].size());
for (int j = 0; j < dp.size(); ++j)
if (obstacleGrid[0][j] == 1)
dp[j] = 0;
else if (j == 0)
dp[j] = 1;
else
dp[j] = dp[j-1];
for (int i = 1; i < obstacleGrid.size(); ++i)
for (int j = 0; j < dp.size(); ++j){
if (obstacleGrid[i][j] == 1)
dp[j] = 0;
else if (j != 0)
dp[j] = dp[j] + dp[j-1];
}
return dp.back();
}
};