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.
思路:DFS,大数据的TLE,需要进行优化
class Solution { public: int ans; void dfs(int i, int j, int step,vector<vector<int> > &obstacleGrid){ if (i == obstacleGrid.size() || j == obstacleGrid[0].size()){ return; } if (obstacleGrid[i][j]){ return; } if (step == obstacleGrid.size() + obstacleGrid[0].size() -1){ ans++; return; } dfs(i+1,j,step + 1,obstacleGrid); dfs(i,j+1,step + 1,obstacleGrid); return; } int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { // Start typing your C/C++ solution below // DO NOT write int main() function ans = 0; dfs(0,0,1,obstacleGrid); return ans; } };
问题:大数据的时候TLE,问题搜索的时候,走了很多重复的子路径
所以不能进行DFS(DFS本质上是暴力),而应该DP
DP[i,j] = 代表从A[0,0]到A[i,j]的path个数
DP[i,j] = A[i-1,j] is'not obstacle ? DP[i-1,j] + A[i,j-1] is'not obstacle DP[i,j-1]
0 1 0 0 0
1 0 0 0 0
0 0 0 0 0 ==》第一行的时候,需要特殊处理,1之后的初值都是0,1之前的才是1
0 0 0 0 0
class Solution { public: int dp(vector<vector<int> > &obstacleGrid){ vector<int> dp(obstacleGrid[0].size(),1); int m = obstacleGrid.size(),n = obstacleGrid[0].size(); //第一行需要特殊处理 bool first = false; for(int j = 0; j < n; j++){ if (obstacleGrid[0][j]){ first = true; } if (obstacleGrid[0][j] || first){ dp[j] = 0; }else{ dp[j] = 1; } } for(int i = 1; i < m; i++){ for(int j = 0; j < n; j++){ //dp[i][j] = dp[i-1][j] + dp[i][j-1]; if (obstacleGrid[i][j]){ //是障碍,说明到当前位置的路径个数是0 dp[j] = 0; }else if (j){ dp[j] = dp[j] + dp[j-1]; } } } return dp[dp.size() -1]; } int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { // Start typing your C/C++ solution below // DO NOT write int main() function return dp(obstacleGrid); } };
浙公网安备 33010602011771号