p114 路径数量(含障碍物)(leetcode 63)
Posted repinkply
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了p114 路径数量(含障碍物)(leetcode 63)相关的知识,希望对你有一定的参考价值。
一:解题思路
方法一:Time:O(m*n),Space:O(m*n)
方法二:Time:O(m*n),Space:O(1)
二:完整代码示例 (C++版和Java版)
方法一C++:
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(), n = obstacleGrid[0].size(); vector<vector<int>> d(m, vector<int>(n)); d[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1; for (int j = 1; j < n; j++) d[0][j] = obstacleGrid[0][j] == 1 ? 0 : d[0][j - 1]; for (int i = 1; i < m; i++) d[i][0] = obstacleGrid[i][0] == 1 ? 0 : d[i - 1][0]; for (int i = 1; i < m; i++) for (int j = 1; j < n; j++) d[i][j] = obstacleGrid[i][j] == 1 ? 0 :((long)d[i - 1][j] + (long)d[i][j - 1]); return d[m - 1][n - 1]; } };
方法一Java:
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m=obstacleGrid.length,n=obstacleGrid[0].length; int[][] d=new int[m][n]; d[0][0]=obstacleGrid[0][0]==1?0:1; for(int j=1;j<n;j++) d[0][j]=obstacleGrid[0][j]==1?0:d[0][j-1]; for(int i=1;i<m;i++) d[i][0]=obstacleGrid[i][0]==1?0:d[i-1][0]; for(int i=1;i<m;i++) { for(int j=1;j<n;j++) { d[i][j]=obstacleGrid[i][j]==1?0:d[i-1][j]+d[i][j-1]; } } return d[m-1][n-1]; } }
方法二C++:
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(), n = obstacleGrid[0].size(); vector<int> d(n,0); d[0] = obstacleGrid[0][0] == 1 ? 0 : 1; for (int i = 0; i < m; i++) { d[0] = obstacleGrid[i][0] == 1 ? 0 : d[0]; for (int j = 1; j < n; j++) d[j] = obstacleGrid[i][j] == 1 ? 0 : (long)d[j] + (long)d[j-1]; } return d[n-1]; } };
方法二Java:
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m=obstacleGrid.length,n=obstacleGrid[0].length; int[] d=new int[n]; d[0]=obstacleGrid[0][0]==1?0:1; for(int i=0;i<m;i++) { d[0]=obstacleGrid[i][0]==1?0:d[0]; for(int j=1;j<n;j++) d[j]=obstacleGrid[i][j]==1?0:d[j]+d[j-1]; } return d[n-1]; } }
以上是关于p114 路径数量(含障碍物)(leetcode 63)的主要内容,如果未能解决你的问题,请参考以下文章
路径规划基于matlab模糊控制机器人路径规划含Matlab源码 1643期
LeetCode 600 不含连续1的非负整数[字典数 动态规划] HERODING的LeetCode之路