2024每日刷题(115)
Leetcode—63. 不同路径 II
动态规划算法思想
实现代码
class Solution {
public:int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int m = obstacleGrid.size();int n = obstacleGrid[0].size();vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));dp[0][1] = 1;for(int i = 1; i <= m; i++) {for(int j = 1; j <= n; j++) {if(!obstacleGrid[i - 1][j - 1]) {dp[i][j] = dp[i - 1][j] + dp[i][j - 1];}}}return dp[m][n];}
};
运行结果
优化版滚动数组实现代码
class Solution {
public:int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int m = obstacleGrid.size();int n = obstacleGrid[0].size();vector<int> dp(n, 0);dp[0] = 1;for(int i = 0; i < m; i++) {for(int j = 0; j < n; j++) {if(obstacleGrid[i][j] == 1) {dp[j] = 0;} else if(j > 0) {dp[j] += dp[j - 1];}}}return dp[n - 1];}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!