题目:63. 不同路径 II
思路
动态规划
预处理有点多;
代码
// f[i][j] : 从起点到[i][j]有多少种路径
// f[i][j] = f[i-1][j] + f[i][j-1], 如果来的路上有障碍物, +0不影响结果
// 最左边一列,最上边一行为 1, 有障碍物为 0;
// i: 0->m-1, j: 0->n-1
// class Solution {
public:int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int i, j;int m = obstacleGrid.size(), n = obstacleGrid[0].size();vector<vector<int>> f(m, vector<int>(n, 0));for(i = 0; i < m; i++){if(obstacleGrid[i][0] == 1 || (i > 0 && obstacleGrid[i-1][0] == 1) || (i > 0 && f[i-1][0] == 0)){f[i][0] = 0;}else{f[i][0] = 1;}}for(j = 0; j < n; j++){if(obstacleGrid[0][j] == 1 || (j > 0 && obstacleGrid[0][j-1] == 1) || (j > 0 && f[0][j-1] == 0)){f[0][j] = 0;}else{f[0][j] = 1;}}for(i = 0; i < m; i++){for(j = 0; j < n; j++){cout << f[i][j];}cout << endl;}cout << endl;for(i = 1; i < m; i++){for(j = 1; j < n; j++){if(obstacleGrid[i-1][j] == 1){f[i-1][j] = 0;}if(obstacleGrid[i][j-1] == 1){f[i][j-1] = 0;}if(obstacleGrid[i][j] == 1){f[i][j] = 0;}else{f[i][j] = f[i-1][j] + f[i][j-1];}}}for(i = 0; i < m; i++){for(j = 0; j < n; j++){cout << f[i][j];}cout << endl;}return f[m-1][n-1];}
};