首页 > 代码库 > Unique Paths II
Unique Paths II
方法一:动态规划
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(),n = obstacleGrid[0].size(); vector<vector<int>> fm = vector<vector<int>>(m, vector<int>(n, 0)); fm[0][0] = (obstacleGrid[0][0] == 1) ? 0 : 1; for(int i=1; i<n; ++i) if(obstacleGrid[0][i] == 1) fm[0][i] = 0; else fm[0][i] = fm[0][i-1]; for(int i=1; i<m; ++i) if(obstacleGrid[i][0] == 1) fm[i][0] = 0; else fm[i][0] = fm[i-1][0]; for(int i=1; i<m; ++i) { for(int j=1; j<n; ++j) { if(obstacleGrid[i][j] == 1) fm[i][j] = 0; else fm[i][j] = fm[i-1][j] + fm[i][j-1]; } } return fm[m-1][n-1]; } };
方法二:备忘录法
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(), n = obstacleGrid[0].size(); fm = vector<vector<int>>(m, vector<int>(n, 0)); fm[0][0] = (obstacleGrid[0][0] == 1) ? 0 : 1; return dfs(obstacleGrid, m-1, n-1); } private: vector<vector<int>> fm; int dfs(vector<vector<int>>& obstacleGrid, int m, int n) { if(m < 0 || n < 0) return 0; if(obstacleGrid[m][n]) return 0; if(m == 0 && n == 0) return fm[0][0]; if(fm[m][n] > 0) return fm[m][n]; else return fm[m][n] = dfs(obstacleGrid, m-1, n) + dfs(obstacleGrid, m, n-1); } };
Unique Paths II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。