首页 > 其他分享 >63.unique-paths-ii 不同路径II

63.unique-paths-ii 不同路径II

时间:2022-10-05 17:36:26浏览次数:81  
标签:vector paths obstacleGrid int else ii 63 II dp

题目描述

63.不同路径II

解题思路

相比62.不同路径II, 主要是多了障碍物地判断,设\(obstacleGrid[i][j] = 0\),则\(dp_{{i}{j}} = 0\),其余递推关系相同。
注意for循环遍历地过程中的条件判断。当i = 0j = 0dp[i][j] = dp[i][j - 1]dp[i][j] = dp[i - 1][j]
dp[0][0] = 0。

代码

#include <vector>
using std::vector;
class Solution {
  public:
    int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        vector<vector<int>> dp(m, vector<int>(n, 0));
        dp[0][0] = 1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) {
                    if (obstacleGrid[i][j] == 1)
                        dp[i][j] = 0;
                    else
                        dp[i][j] = 1;
                } else {
                    if (obstacleGrid[i][j] == 1)
                        dp[i][j] = 0;
                    else {
                        if (i == 0)
                            dp[i][j] = dp[i][j - 1];
                        else if (j == 0)
                            dp[i][j] = dp[i - 1][j];
                        else
                            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                    }
                }
            }
        }
        return dp[m - 1][n - 1];
    }
};

标签:vector,paths,obstacleGrid,int,else,ii,63,II,dp
From: https://www.cnblogs.com/zwyyy456/p/16755941.html

相关文章