62. 不同路径
题目链接:https://leetcode.cn/problems/unique-paths/
题目难度:中等
文章讲解:https://programmercarl.com/0062.不同路径.html
视频讲解:https://www.bilibili.com/video/BV1ve4y1x7Eu/
题目状态:还是想不出 dp 数组,看题解了
思路:
首先构建一个 dp 数组,这次是一个二维数组,dp[i][j] 表示从 (0, 0) 到 (i, j)的路径个数。很容易想到:dp[1][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, 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];}
};
63. 不同路径 II
题目链接:https://leetcode.cn/problems/unique-paths-ii/
题目难度:中等
文章讲解:https://programmercarl.com/0063.不同路径II.html
视频讲解:https://www.bilibili.com/video/BV1Ld4y1k7c6/
题目状态:能想到怎么解,但参数输入给我看懵了
思路:
和上面一题思路差不多,只不过是要判断一下当前位置是否有障碍物,若有障碍物就过不来,因此到达障碍物的路径依旧是0,还要注意的一点是,若在边缘中某一位置出现在障碍物,则该位置到其后面一直都过不去,因此后面一直都是 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 - 1][j] + dp[i][j - 1];}}return dp[m - 1][n - 1];}
};
343. 整数拆分
题目链接:https://leetcode.cn/problems/integer-break/
题目难度:中等
文章讲解:https://programmercarl.com/0343.整数拆分.html
视频讲解:https://www.bilibili.com/video/BV1Mg411q7YJ/
题目状态:看题解了
思路:
分开遍历整数,将其拆为 i 和 j,结果为 i * j,找到 i * j 的最大值。而后面一个整数的乘积也可以通过前一个拆分出来的整数的乘积最大值再乘剩余的部分得出。
代码:
class Solution {
public:int integerBreak(int n) {vector<int> dp(n + 1);dp[2] = 1;for(int i = 3; i <= n; ++i) {for(int j = 1; j <= i / 2; ++j) {dp[i] = max(dp[i], max((i - j) * j, dp[i - j] * j));}}return dp[n];}
};
也可以使用贪心算法,但是没有看太懂,代码如下:
class Solution {
public:int integerBreak(int n) {if (n == 2) return 1;if (n == 3) return 2;if (n == 4) return 4;int result = 1;while (n > 4) {result *= 3;n -= 3;}result *= n;return result;}
};
96. 不同的二叉搜索树
题目链接:https://leetcode.cn/problems/unique-binary-search-trees/
题目难度:中等
文章讲解:https://programmercarl.com/0096.不同的二叉搜索树.html
视频讲解:https://www.bilibili.com/video/BV1eK411o7QA/
题目状态:看完题一点思路没有,看题解
思路:
将二叉搜索树拆分,按其左右子树分别往下拆,最后将左右子树得到的二叉搜索树的个数相加获得。
代码:
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];}
};