Leetcode解题笔记 63. Unique Paths II [Medium] 动态规划

来源:互联网 发布:朗文英英词典 mac 编辑:程序博客网 时间:2024/06/01 07:12

解题思路

其实就是要添加一步,当是障碍时,取0,其余同上一题的解题思路。

代码

class Solution {public:    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {        int row = obstacleGrid.size();        int col = obstacleGrid[0].size();        vector<vector<int>> v(row);        for (int i = 0; i < row; i++) {            v[i].resize(col);        }        if (obstacleGrid[0][0] == 1) {            return 0;        } else {            v[0][0] = 1;        }        for (int i = 1; i < row; i++) {            v[i][0] = obstacleGrid[i][0] == 1 ? 0 : v[i - 1][0];        }        for (int i = 1; i < col; i++) {            v[0][i] = obstacleGrid[0][i] == 1 ? 0 : v[0][i - 1];        }        for (int i = 1; i < row; i++) {            for(int j = 1; j < col; j++) {                v[i][j] = obstacleGrid[i][j] == 1 ? 0 : v[i][j - 1] + v[i - 1][j];            }        }        return v[row - 1][col - 1];    }};
原创粉丝点击