Unique Pathside
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).spa
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).code
How many possible unique paths are there?blog
Above is a 3 x 7 grid. How many possible unique paths are there?it
Note: m and n will be at most 100.io
題意:給定一個m*n的二維方格,從方格的左上角開始走,每次只能向下或者向右走一步直到方格的右下角結束,求總共有多少條不一樣路徑。table
解題:從左上角走到右下角,每次只能向下或者向右走一步,無論怎麼走都須要m+n-2步才能走到,而這其中有m-1步是向下走,有n-1是向右走,只用從這m+n-2個位置中選擇m-1個位置,則剩餘的位置表示向右走。容易求得值是Cm-1m+n-2,利用楊輝三角便可。function
Unique Paths IIclass
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.
在問題二中放置了一些障礙物,1表示有障礙物,0表示能夠走,求總共有多少條不重複路徑。
解題:看到這個題的第一反映是使用廣度優先搜索或者深度優先搜索找出全部的路徑,嘗試以後發現超時,只好另想方法。
由於每次都只能向下和向右行走,所以對每一個方格來講只能從它左邊和上邊的格子進入當前方格,從起點開始到達當前方格的路徑數量也就等於從起點開始分別到它左邊和上邊方格的路徑數的總和。
根據上邊的思路能夠求出從起點到每個方格的路徑個數(若是方格中放置了障礙物則不可經過)
1 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 2 |
1 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 int m = obstacleGrid.size(); 5 if(m<=0){ 6 return 0; 7 } 8 int n = obstacleGrid[0].size(); 9 if(n<=0){ 10 return 0; 11 } 12 if(obstacleGrid[0][0]==1){ 13 return 0; 14 } 15 16 int map[101][101]; 17 map[0][0]=1; 18 for(int i=1;i<m;i++){ 19 if(obstacleGrid[i][0]==1) 20 map[i][0]=0; 21 else 22 map[i][0]=map[i-1][0]; 23 } 24 for(int i=1;i<n;i++){ 25 if(obstacleGrid[0][i]==1) 26 map[0][i]=0; 27 else 28 map[0][i]=map[0][i-1]; 29 } 30 for(int i=1;i<m;i++) 31 for(int j=1;j<n;j++){ 32 if(obstacleGrid[i][j]==1){ 33 map[i][j]=0; 34 } 35 else 36 map[i][j]=map[i-1][j]+map[i][j-1]; 37 } 38 39 return map[m-1][n-1]; 40 }