首页 > 代码库 > leetcode 刷题记

leetcode 刷题记

1 63. Unique Paths II   带障碍物的路径计算

思路:dp[i][j] = 0 if grid[i][j] = 1 (障碍物)

        再按照无障碍物的逻辑进行计算

技术分享
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int rows = obstacleGrid.size();
        if (rows == 0) {
            return 0;
        }
        int cols = obstacleGrid[0].size();
        vector<vector<int>> ways(rows, vector<int> (cols, 1));
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (obstacleGrid[i][j] == 1) {
                    ways[i][j] = 0;
                } else {
                    if (i == 0 && j == 0) {
                        ways[i][j] = 1;
                    } else if (i == 0) {
                        ways[i][j] =  ways[i][j - 1];
                    } else if (j == 0) {
                        ways[i][j] = ways[i - 1][j];
                    } else {
                        ways[i][j] = ways[i - 1][j] + ways[i][j - 1];
                    }
                }
            }
        }
        return ways[rows - 1][cols - 1];
    }
View Code

 

leetcode 刷题记