2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
The value of each cell is determined by the cells above and to the left, so you need to initialize the top and left cells first. Because the question requires you to move only downward and to the right, the top and left cells are initialized to 1.
time complexity:
O
(
m
∗
n
)
O(m*n)
O(m∗n)
Space complexity:
O
(
m
∗
n
)
O(m*n)
O(m∗n)
// c++
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector(n,0));
for(int i=0; i<m; i++) dp[i][0] = 1;
for(int j=0; j<n; j++) dp[0][j] = 1;
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
The idea is similar to the previous problem, but obstacles are added on the basis of the previous problem. The dp array represents the number of paths to reach the cell (i, j), and the obstacle position in the dp array is 0. When the first row and the first column are initialized, if an obstacle appears in the path, the cells behind the obstacle cannot be reached, and the corresponding dp array values are all 0.
time complexity:
O
(
m
∗
n
)
O(m*n)
O(m∗n)
Space complexity:
O
(
m
∗
n
)
O(m*n)
O(m∗n)
// c++
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
vector<vector<int>> dp(obstacleGrid.size(), vector(obstacleGrid[0].size(), 0));
// 标志单元格是否可到达
bool flag = true;
// 初始化第一行
for(int i=0; i<obstacleGrid.size(); i++){
if(obstacleGrid[i][0] == 1) {
// 可以直接break
flag = false;
}
if(flag) dp[i][0] = 1;
else dp[i][0] = 0;
}
// 标志单元格是否可到达
flag = true;
// 初始化第一列
for(int j=0; j<obstacleGrid[0].size(); j++){
if(obstacleGrid[0][j] == 1) {
// 可以直接break
flag = false;
}
if(flag) dp[0][j] = 1;
else dp[0][j] = 0;
}
// 计算dp数组
for(int i=1; i<obstacleGrid.size(); i++){
for(int j=1; j<obstacleGrid[0].size(); j++){
if(obstacleGrid[i][j]==1) continue;
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[obstacleGrid.size()-1][obstacleGrid[0].size()-1];
}
};