62.不同路径
- dp[i][j]: 到达(i, j)位置有多少种方法
- 递推公式:dp[i][j] = dp[i-1][j] + dp[i][j-1]
- 初始化dp[0][j] = 1只有向右一种走法, dp[i][0] = 1只有向下一种走法;
- 遍历顺序:从左向右
- 打印dp数组
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n));
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(i == 0 && j == 0) dp[i][j] = 1;
else if(j == 0 && i > 0) {
dp[i][j] = 1;
} else if(i == 0 && j > 0) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i - 1][j] + dp[i][j-1];
}
}
}
for(auto vec : dp) {
for(int val : vec) cout << val << " ";
}
return dp[m-1][n-1];
}
};
63.不同路径II
- dp[i][j]: 到达dp[i][j]最多的路径
- 递推公式:dp[i][j] = dp[i-1][j] + dp[i][j-1]
- 初始化:dp[i][0]=1,如果有障碍的话后面都初始化为0;dp[0][j]=1,如果有障碍的话,后面都初始化为0
- 遍历顺序:从左向右遍历
- 打印dp数组
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int row = obstacleGrid.size();
int col = obstacleGrid[0].size();
vector<vector<int>> dp(row, vector<int>(col));
if(obstacleGrid[0][0] == 1) dp[0][0] = 0;
else dp[0][0] = 1;
for(int i = 1; i < row; ++i) {
if(obstacleGrid[i][0] == 1) dp[i][0] = 0;
else dp[i][0] = dp[i-1][0];
}
for(int i = 1; i < col; ++i) {
if(obstacleGrid[0][i] == 1) dp[0][i] = 0;
else dp[0][i] = dp[0][i-1];
}
for(int i = 1; i < row; ++i) {
for(int j = 1; j < col; ++j) {
if(obstacleGrid[i][j] == 1) dp[i][j] == 0;
else {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
}
for(auto vec : dp) {
for(int val : vec) cout << val << "\t";
cout << endl;
}
return dp[row-1][col-1];
}
};
343.整数拆分
- dp[i]:i拆分之后的最大乘积
- 递推公式:dp[i] = j * dp[i - j], j=[1, i / 2]
- 初始化:dp[0]=0, dp[1]=0, dp[2]=1;
- 遍历顺序:从小到大一次遍历
- 打印dp数组
class Solution {
public:
int integerBreak(int n) {
vector<int> dp(n + 1);
dp[0] = 0, dp[1] = 0, dp[2] = 1;
for(int i = 3; i <= n; ++i) {
for(int j = 1; j <= i / 2; ++j) {
dp[i] = max(max(j * (i - j), j * dp[i-j]), dp[i]);
}
}
for(int i = 0; i <= n; ++i) cout << dp[i] << " ";
return dp[n];
}
};
96.不同的二叉搜索树
- dp[i]:有i个节点的二叉搜索树有多少种不同的形状
- 递推公式:dp[i] += dp[j-1]*dp[i-j] (j=[1, i])。dp[j-1]表示以j为根节点时,左子树的不同形状数;dp[i-j]表示j为根节点时,右子树的不同形状数
- 初始化:dp[0]=1,空节点是二叉搜索树,只有一种形状
空二叉树既是满二叉树,又是平衡二叉树,还是二叉搜索树 - 遍历顺序:从小到大依次遍历
- 打印dp数组
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1);
dp[0] = 1;
for(int i = 1; i <= n; ++i) {
for(int j = 1; j < i; ++j) {
dp[i] += dp[j-1] * dp[i-j];
}
}
return dp[n];
}
};
标签:obstacleGrid,int,不同,路径,随想录,else,vector,遍历,dp
From: https://www.cnblogs.com/cscpp/p/18248760