您的位置:首页 > 产品设计 > UI/UE

leetCode+Unique Paths II

2015-11-22 22:09 417 查看
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,
ere is one obstacle in the middle of a 3 × 3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
e total number of unique paths is 2.
Note: m and n will be at most 100.

方法一:DFS

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if(obstacleGrid.empty()) return 0;

int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] || obstacleGrid[m-1][n-1]) return 0;

int **buffer = new int* [m+1];
for(int i=0;i<=m;i++){
buffer[i] = new int [n+1];
fill(buffer[i],buffer[i]+n+1,0);
}
int temp = dfs(obstacleGrid,m,n,buffer);
for(int i=0;i<=m;i++)
delete [] buffer[i];
delete [] buffer;
return temp;
}

int dfs(vector<vector<int>> &obstacleGrid,int x,int y,int** buf){
if(x < 1 || y < 1) return 0;
if(obstacleGrid[x-1][y-1]) return 0;
if(buf[x][y]>0) return buf[x][y];
if(x == 1 && y==1 ) return 1;

buf[x-1][y] = dfs(obstacleGrid, x-1, y, buf);
buf[x][y-1] = dfs(obstacleGrid, x, y-1, buf);
return buf[x][y] = buf[x-1][y]+buf[x][y-1];
}
};


方法二:DP

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if(obstacleGrid.empty()) return 0;

int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] || obstacleGrid[m-1][n-1]) return 0;
int *buf = new int
;
fill(buf,buf+n,0);

buf[0] = 1;
for(int i=0;i < m;i++){
for(int j=0;j<n;j++){
buf[j] = obstacleGrid[i][j] ? 0 : (j == 0 ? 0 : buf[j-1]) + buf[j];
}
}
return buf[n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: