碎碎念:加油
参考:代码随想录
62.不同路径
题目链接
思想
动态规划五部曲:
- 确定dp数组以及下标的含义:dp[i][j] 从start出发走到i,j有多少种走法
- 确定递推公式:dp[i][j] = dp[i-1][j]+dp[i][j-1]
- dp数组的初始化:dp[0][j]=1 dp[i][0]=1,需要初始化的范围如图中红色范围
- 确定遍历顺序:从左往右遍历,从上往下遍历
- 打印dp数组:主要用来debug
题解
// cpp
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(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][j - 1] + dp[i - 1][j];
printf("%d", dp[i][j]);
}
}
return dp[m - 1][n - 1];
}
};
# python
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [1] * n
for j in range(1, m):
for i in range(1, n):
dp[i] += dp[i - 1]
return dp[n - 1]
反思
本题也可以优化,用一个一维数组即可,见python代码。【不太熟悉,二刷再看】
63. 不同路径 II
题目链接
思想
和上一题的区别在于,网格中可能有障碍。
动态规划五部曲:
- 确定dp数组以及下标的含义:dp[i][j] 从start出发走到i,j有多少种走法
- 确定递推公式:需要判断一下i,j的位置是不是障碍,如果不是dp[i][j] = dp[i-1][j]+dp[i][j-1]
- dp数组的初始化:dp[0][j]=1 dp[i][0]=1,需要初始化的范围如图中绿色范围,一旦遇到障碍,初始化的for循环要立刻结束
- 确定遍历顺序:从左往右遍历,从上往下遍历
- 打印dp数组:主要用来debug
如果起始位置或者终止位置是障碍的话,直接返回0。
题解
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) return 0;
vector<vector<int>> dp(m, vector<int>(n, 0));
// 初始化
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) dp[i][0] = 1;
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) dp[0][j] = 1;
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 1) continue;
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
return dp[m - 1][n - 1];
}
};
# python
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
if obstacleGrid[m - 1][n - 1] == 1 or obstacleGrid[0][0] == 1:
return 0
dp = [[0] * n for _ in range(m)]
for i in range(m):
if obstacleGrid[i][0] == 0:
dp[i][0] = 1
else:
break
for j in range(n):
if obstacleGrid[0][j] == 0:
dp[0][j] = 1
else:
break
for i in range(1, m):
for j in range(1, n):
if obstacleGrid[i][j] == 1:
continue
else:
dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
return dp[m - 1][n - 1]
反思
注意:如果起始位置或者终止位置是障碍的话,直接返回0。
343. 整数拆分
题目链接
思想
应该尽可能将整数拆分为相同的数。
动态规划五部曲:
- 确定dp数组以及下标的含义:dp[i] 对i拆分,拆分得到的数的最大乘积
- 确定递推公式:dp[i] = max(j* dp[i-j], j*(i-j), dp[i])
- dp数组的初始化:dp[2]=1 【dp[0]和dp[1]没有意义,不过可以设置为0】
- 确定遍历顺序:i从3开始遍历,从左往右遍历,j从1开始,j<i/2,递推公式
- 打印dp数组:主要用来debug
题解
// cpp
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(dp[i], max(j * (i - j), j * dp[i - j]));
}
}
return dp[n];
}
};
# python
class Solution:
def integerBreak(self, n: int) -> int:
dp = [0] * (n + 1)
dp[2] = 1
for i in range(3, n + 1):
for j in range(1, int(i / 2) + 1):
dp[i] = max(dp[i], j * (i - j), j * dp[i - j])
return dp[n]