62. Unique Paths
做得第一个二维动态规划,还是比较简单,先遍历列,每列遍历完然后遍历下一行,犯的错误以及代码如下
class Solution {
public:
int uniquePaths(int m, int n) {
// vector<int> dp[n*m+1];这里傻逼了,这要创建二维数组,记一下二维vector的初始化方法
vector<vector<int>> dp(m,vector<int>(n,0));
for(int i=0;i<m;i++){
dp[i][0] =1; //i is for m, which is row
}
for(int j=0;j<n;j++){
dp[0][j] =1; // j is for N, which is column
}
//for(int i=1,j=1; i<m,j<n;i++,j++){
// dp[i][j] = dp[i-1][j] +dp[i][i-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];
}
};
63. Unique Paths II
简单题目,注意当obstacle不等于0 的时候直接continue,这样那个格子就会保持初值
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m =obstacleGrid.size(); //二维数组直接取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));
for (int i = 0; i < m && obstacleGrid[i][0] != 1; i++){
dp[i][0] =1; //i is for m, which is row
}
for (int j = 0; j < n && obstacleGrid[0][j] != 1; j++){
dp[0][j] =1; // j is for N, which is column
}
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 table(dp数组)保持初始值(0)就可以了。这里直接continue所以就不会改变这个格子的数据,就会是一开始初始化的数据0
dp[i][j] = dp[i-1][j] +dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};