一、不同路径
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m+1,vector<int>(n+1));
dp[0][1] = 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][n];
}
};
二、不同路径II
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& ob) {
int m = ob.size();
int n = ob[0].size();
vector<vector<int>> dp(m+1,vector<int>(n+1));
dp[1][0] = 1;
for(int i = 1;i <= m;i++){
for(int j = 1;j <= n;j++){
if(ob[i-1][j-1] == 0)
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m][n];
}
};
三、礼物的最大价值
class Solution {
public:
int maxValue(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m+1,vector<int>(n+1));
for(int i = 1;i <= m;i++){
for(int j = 1;j <= n;j++){
dp[i][j] = max(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1];
}
}
return dp[m][n];
}
};
四、下降路径最小和
class Solution {
public:
int minFallingPathSum(vector<vector<int>>& matrix) {
int n = matrix.size();
vector<vector<int>> dp(n+1,vector<int> (n+2,INT_MAX));
for(int j = 0;j < n+2;j++){
dp[0][j] = 0;
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i-1][j+1]))+matrix[i-1][j-1];
}
}
int ret = INT_MAX;
for(int i = 1;i <= n;i++)
ret = min(ret,dp[n][i]);
return ret;
}
};
五、最小路径和
此题跟前面差不多,略。
六、地下城游戏 【以[i,j]位置为起点】
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int m = dungeon.size(),n = dungeon[0].size();
vector<vector<int>> dp(m+1,vector(n+1,INT_MAX));
dp[m][n-1] = dp[m-1][n] = 1;
for(int i = m - 1;i >= 0;i--){
for(int j = n - 1;j >=0;j--){
dp[i][j] = min(dp[i+1][j],dp[i][j+1]) - dungeon[i][j];
dp[i][j] = max(1,dp[i][j]);
}
}
return dp[0][0];
}
};