LeetCode62. 不同路径
题目链接:62. 不同路径
独上高楼,望尽天涯路
第一次接触二维的dp数组,初始化会麻烦一点,dp数组表示的是机器人移动到第i行第j列格子的所有路径数。
class Solution {
public:
int uniquePaths(int m, int n) {
if (m == 1 || n == 1) return 1;
vector<vector<int>> dp(m, vector<int>(n));
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];
}
};
慕然回首,灯火阑珊处
思路一样。
LeetCode63. 不同路径II
题目链接:63. 不同路径II
独上高楼,望尽天涯路
和上一道题思路大致一样,不同的是不管在初始化还是递推过程中,遇到石头的话就跳过去就好了。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) return 0;
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m; i++) {
if (obstacleGrid[i][0] == 1) break;
dp[i][0] = 1;
}
for (int j = 0; j < n; j++) {
if (obstacleGrid[0][j] == 1) break;
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];
}
};
慕然回首,灯火阑珊处
思路一样, 动态规划的开头还是挺顺利的。
标签:vector,LeetCode63,obstacleGrid,int,路径,++,LeetCode62,dp From: https://www.cnblogs.com/BarcelonaTong/p/17089501.html