不同路径
使用动态规划算法
dp[i][j]
代表走到第i行第j列有多少路径dp[0][j]
只能由dp[0][j-1]
走来dp[i][0]
只能由dp[i-1][0]
走来
if(i == 0 && j != 0)dp[i][j] = dp[i][j - 1];
else if(j == 0 && i != 0)dp[i][j] = dp[i - 1][j];
else if(!i && !j)continue;
else dp[i][j] = dp[i-1][j] + dp[i][j-1];
代码
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m,vector<int>(n));
dp[0][0] = 1;
//初始化dp[0][j]只能由dp[0][j-1]走来dp[i][0]只能由dp[i-1][0]走来
for(int i = 0;i < m;++i){
for(int j = 0;j < n;++j){
if(i == 0 && j != 0)dp[i][j] = dp[i][j - 1];
else if(j == 0 && i != 0)dp[i][j] = dp[i - 1][j];
else if(!i && !j)continue;
else dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
//dp[i][j]代表走到第i行第j列有多少路径
不同路径2
不同路径2
对比1添加了不同的条件:由障碍物
- 遇到障碍物直接标为0就可以
- 如果开始和结尾有一个是障碍物,那就无法走到,直接返回0
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] || obstacleGrid[m-1][n-1])return 0;
vector<vector<int>> dp(m,vector<int>(n));
dp[0][0] = 1;
for(int i = 0;i < m;++i){
for(int j = 0;j < n;++j){
if(i == 0 && j == 0)continue;
if(obstacleGrid[i][j])dp[i][j] = 0;
else if(i == 0)dp[i][j] = dp[i][j - 1];
else if(j == 0)dp[i][j] = dp[i-1][j];
else dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
最小路径和
最小路径和
同上
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m,vector<int>(n));
dp[0][0] = grid[0][0];
for(int i = 0;i < m;++i){
for(int j = 0;j < n;++j){
if(i == 0 && j == 0)continue;
if(i == 0)dp[i][j] = dp[i][j-1] + grid[i][j];
else if(j == 0)dp[i][j] = dp[i - 1][j] + grid[i][j];
else dp[i][j] = min(dp[i][j-1],dp[i - 1][j]) + grid[i][j];
}
}
return dp[m-1][n-1];
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)