Unique Paths and Unique Paths II
阿新 • • 發佈:2019-02-17
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 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). How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
這個題本來是想用回溯法來做,用一個count進行累加,規模小的時候可以,但規模一大就超時了。回溯法程式碼:
class Solution {
public:
int count;
int uniquePaths(int m, int n) {
count=0;
find(0,0,m,n);
return count;
}
void find(int row,int col,int m,int n){
if(row==m-1 && col==n-1)
count++;
if(row<m-1)
find(row+1,col,m,n);
if(col<n-1)
find(row,col+1,m,n);
}
};
於是轉而用動態規劃進行解題。到達每個節點的路徑的總數都是到達該節點左邊節點的路徑總數,加上到達該節點上面節點的路徑總數。設定一個初始二維陣列,值都設為1,然後依次進行累加即可。
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> count(m,vector<int>(n,1));
for(int i=1;i<m;i++)
for(int j=1;j<n;j++)
count[i][j]=count[i-1][j]+count[i][j-1];
return count[m-1][n-1];
}
};
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.
這個題目是在1的裡面添加了障礙物,方法還是動態規劃,但是初值都賦為0.然後對第一行和第一列進行初始化。在累加的時候,判斷一下當前位置是不是障礙物,如果是,就賦為0,不是再進行累加,程式碼如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m=obstacleGrid.size();
int n=obstacleGrid[0].size();
vector<vector<int>> count(m,vector<int>(n,0));
if(obstacleGrid[0][0]==0)
count[0][0]=1;
for(int i=1;i<m;i++){
if(obstacleGrid[i][0]==0)
count[i][0]=count[i-1][0];
else
count[i][0]=0;
}
for(int j=1;j<n;j++){
if(obstacleGrid[0][j]==0)
count[0][j]=count[0][j-1];
else
count[0][j]=0;
}
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
if(obstacleGrid[i][j]==0)
count[i][j]=count[i-1][j]+count[i][j-1];
else
count[i][j]=0;
}
}
return count[m-1][n-1];
}
};