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
方法二:DP
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]; } };
相关文章推荐
- leetcode Implement Queue using Stacks
- scala的futue和promise
- HDU 1005 Number Sequence
- iOS中UIButton的titleEdgeInsets和imageEdgeInsets
- EqualsBuilder和HashCodeBuilder
- 不同浏览器对URI以及queryString是如何编码的?
- 模块化以及requirejs和seajs
- BestCoder Round #63 (div.2) HDOJ5568 sequence2(dp + 大数)
- SQL Server replication requires the actual server name to make a connection to the server
- String,StringBuffer,StringBuilder效率与内存占用比较
- UI基础控件整理版
- 《leetCode》:Unique Paths II
- Error when launching Quest Central for DB2: "QCC10000E - Unable to allocate environment handle fo
- easyui-基础组件panel
- 《leetCode》:Unique Paths
- Maven实战(一)---Maven Build--缺少Jar包
- 两个线程与stringbuffer和stringbuiler以及lock synchronized线程测试
- iOS-UIButton和UIImageView的区别
- easyui-Messager(消息窗口)源代码
- easyui-Messager(消息窗口)-2