Unique Paths II
思路和Unique paths 差不多,但是由于有了障碍物,所以,初始化dp矩阵的时候,初始化为0___________________________________________________
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { if (obstacleGrid.empty() || obstacleGrid[0].empty() || obstacleGrid[0][0] == 1) return 0; int m=obstacleGrid[0].size(),n=obstacleGrid.size(); vector<vector<int>> path(n,vector<int>(m,0)); path[0][0]=1; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ if(i==0&&j>0)path[i][j]=path[i][j-1];//第一次做的时候做错了,没有考虑到障碍物把路都封死的情况,写成了path[i][j]=1; if(j==0&&i>0)path[i][j]=path[i-1][j]; if(i>0&&j>0)path[i][j]=path[i-1][j]+path[i][j-1]; if(obstacleGrid[i][j]==1)path[i][j]=0; } return path[n-1][m-1]; } };
Runtime: 4 ms, faster than 52.68% of C++ online submissions for Unique Paths II.速度比较慢,看看大佬的写法
看讨论区说这个是0ms,然而我运行还是4ms,23333
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { int m = obstacleGrid.size() , n = obstacleGrid[0].size(); vector<vector<int>> dp(m+1,vector<int>(n+1,0)); dp[0][1] = 1; for(int i = 1 ; i <= m ; ++i) for(int j = 1 ; j <= n ; ++j) if(!obstacleGrid[i-1][j-1]) dp[i][j] = dp[i-1][j]+dp[i][j-1]; return dp[m][n]; } };