首页 > 代码库 > Unique Paths II
Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0]]
The total number of unique paths is 2
.
Note: m and n will be at most 100.
1 class Solution { 2 public: 3 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { 4 int m = obstacleGrid.size(); 5 if(m == 0) return 0; 6 int n = obstacleGrid[0].size(); 7 8 vector<int> row(n,0); 9 vector<vector<int>> record(m,row);10 11 bool obstacle = false;12 for(int i = n-1; i >= 0; i--){13 if(obstacle)14 record[m-1][i] = 0;15 else if(obstacleGrid[m-1][i] == 1){16 obstacle = true;17 record[m-1][i] = 0;18 }else record[m-1][i] = 1;19 }20 obstacle = false;21 for(int i = m-1; i >= 0; i--){22 if(obstacle)23 record[i][n-1] = 0;24 else if(obstacleGrid[i][n-1] == 1){25 obstacle = true;26 record[i][n-1] = 0;27 }else record[i][n-1] = 1;28 29 }30 for(int i = m-2; i >= 0; i--)31 for(int j = n-2; j >= 0; j--){32 if(obstacleGrid[i][j] == 1) record[i][j] = 0;33 else record[i][j] = record[i+1][j] + record[i][j+1];34 }35 return record[0][0];36 }37 };
动态规划,时间复杂度O(m*n), 空间复杂度O(m*n)。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。