所有的LeetCode題解索引,可以看這篇文章——【算法和數(shù)據(jù)結(jié)構(gòu)】LeetCode題解。
一、題目
二、解法
??思路分析:參考【算法與數(shù)據(jù)結(jié)構(gòu)】62、LeetCode不同路徑的題目,可以發(fā)現(xiàn)本題僅僅是多了障礙物。我們還是用動(dòng)態(tài)規(guī)劃來做。有障礙物的地方無法到達(dá),因此路徑數(shù)量為0,只需要將障礙物位置的dp數(shù)組記為0,除此之外障礙物后面的位置有可能無法到達(dá)(程序當(dāng)中的兩個(gè)if break語句)。
??程序如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int row = obstacleGrid.size(), col = obstacleGrid[0].size();
vector<vector<int>> dp(row, vector<int>(col, 0));
for (int i = 0; i < col; i++) {
if (obstacleGrid[0][i] == 1) break;
dp[0][i] = 1;
}
for (int j = 0; j < row; j++) {
if (obstacleGrid[j][0] == 1) break;
dp[j][0] = 1;
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (obstacleGrid[i][j] == 0) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
else dp[i][j] = 0;
}
}
return dp[row - 1][col - 1];
}
};
復(fù)雜度分析:文章來源:http://www.zghlxwxcb.cn/news/detail-783863.html
- 時(shí)間復(fù)雜度: O ( r o w ? c o l ) O(row*col) O(row?col),,row和col分別是地圖的行和列。
- 空間復(fù)雜度: O ( r o w ? c o l ) O(row*col) O(row?col)。
三、完整代碼
# include <iostream>
# include <vector>
using namespace std;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int row = obstacleGrid.size(), col = obstacleGrid[0].size();
vector<vector<int>> dp(row, vector<int>(col, 0));
for (int i = 0; i < col; i++) {
if (obstacleGrid[0][i] == 1) break;
dp[0][i] = 1;
}
for (int j = 0; j < row; j++) {
if (obstacleGrid[j][0] == 1) break;
dp[j][0] = 1;
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (obstacleGrid[i][j] == 0) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
else dp[i][j] = 0;
}
}
return dp[row - 1][col - 1];
}
};
int main() {
//vector<vector<int>> obstacleGrid = { {0, 0, 0}, {0, 1, 0}, { 0, 0, 0 } };
vector<vector<int>> obstacleGrid = { {0, 1}, {0, 0} };
Solution s1;
int result = s1.uniquePathsWithObstacles(obstacleGrid);
cout << result << endl;
system("pause");
return 0;
}
end文章來源地址http://www.zghlxwxcb.cn/news/detail-783863.html
到了這里,關(guān)于【算法與數(shù)據(jù)結(jié)構(gòu)】63、LeetCode不同路徑 II的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!