題目62:Unique Paths
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?
問題解析:
在一個矩陣中,從左上角開始,每一步只能向下移動一步或者向右移動一步,到右下角停止,總共有多少種不同的路徑?
鏈接:
思路標籤:
算法:DP
數據結構:Vector
解答:
1. C++
- 典型的動態規劃題目;
- 定義m*n的矩陣,arr[i][j]表示到達第i行第j列的位置時有多少種不同的路徑;
- 因爲只能向下或者向右移動,所以很明顯arr[i][j]=arr[i-1][j] + arr[i][j-1];
- 構建二維數組即可解決,但是空間複雜度爲O(m*n);
- 簡化重複子問題,我們每次只用到上一步的前一個結果和上一步的當前結果,所以用一個數組表示即可。arr[i] = arr[i] + arr[i-1]。
class Solution {
public:
int uniquePaths(int m, int n) {
if(m > n)
return uniquePaths(n, m);
vector<int > result(m, 1);
for(int i=1; i<n; ++i){
for(int j=1; j<m; ++j)
result[j] += result[j-1];
}
return result[m-1];
}
};
題目63: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.
問題解析:
題目在62的基礎上爲網格中增加限制障礙塊,有障礙的位置不能走。
鏈接:
思路標籤:
算法:DP
數據結構:Vector
解答:
1. 使用二維數組的動態規劃:
- 與62動態規劃思想是相同的
- 不同的是因爲存在障礙塊,所以並不是所有的路徑都能走通,所以我們將動態規劃的數組全部置爲0,大小爲左和上各增加一行0行,以便進行計算;
- 因爲開始在起始位置,所以dp[0][1] = 1,或者dp[1][0] = 1;
- 在有障礙塊,也就是位置不爲0的地方,不進行dp矩陣的計算,也就是相應位置保持爲0。
- 空間複雜度O(n*m)
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector <int>> dp(m+1, vector<int>(n+1, 0));
dp[0][1] = 1;
for(int i=1; i<=m; i++){
for(int j=1; j<=n; j++){
if(!obstacleGrid[i-1][j-1])
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m][n];
}
};
2. 使用一維數組的動態規劃:
- 與62動態規劃思想相同的
- 上面的解法同樣存在着重複的子問題,所以我們使用一維數組進行簡化;
- 但是不同的是,我們需要在過程中判斷該位置的計算是否是障礙,如果是障礙,那麼此時數組該位置的值變爲0,否則爲上一個值加前一個當前值。
- 空間複雜度:O(m)
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<int > dp(m+1, 0);
dp[1] = 1;
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
if(obstacleGrid[j-1][i-1])
dp[j] = 0;
else
dp[j] += dp[j-1];
}
}
return dp[m];
}
};