Merge branch 'master' into patch-51

This commit is contained in:
程序员Carl 2023-08-04 09:35:54 +08:00 committed by GitHub
commit 00dbf433c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
166 changed files with 2263 additions and 1287 deletions

View File

@ -5,11 +5,11 @@
> 1. **介绍** :本项目是一套完整的刷题计划,旨在帮助大家少走弯路,循序渐进学算法,[关注作者](#关于作者)
> 2. **正式出版** [《代码随想录》](https://programmercarl.com/other/publish.html) 。
> 3. **PDF版本** [「代码随想录」算法精讲 PDF 版本](https://programmercarl.com/other/algo_pdf.html) 。
> 4. **算法公开课** [《代码随想录》算法视频公开课](https://www.bilibili.com/video/BV1fA4y1o715) 。
> 4. **算法公开课** [《代码随想录》算法视频公开课](https://www.programmercarl.com/other/gongkaike.html) 。
> 5. **最强八股文** [代码随想录知识星球精华PDF](https://www.programmercarl.com/other/kstar_baguwen.html) 。
> 6. **刷题顺序** README已经将刷题顺序排好了按照顺序一道一道刷就可以。
> 7. **学习社区** :一起学习打卡/面试技巧/如何选择offer/大厂内推/职场规则/简历修改/技术分享/程序人生。欢迎加入[「代码随想录」知识星球](https://programmercarl.com/other/kstar.html) 。
> 8. **提交代码** 本项目统一使用C++语言进行讲解但已经有Java、Python、Go、JavaScript等等多语言版本感谢[这里的每一位贡献者](https://github.com/youngyangyang04/leetcode-master/graphs/contributors),如果你也想贡献代码点亮你的头像,[点击这里](https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A)了解提交代码的方式。
> 8. **提交代码** 本项目统一使用C++语言进行讲解但已经有Java、Python、Go、JavaScript等等多语言版本感谢[这里的每一位贡献者](https://github.com/youngyangyang04/leetcode-master/graphs/contributors),如果你也想贡献代码点亮你的头像,[点击这里](https://www.programmercarl.com/qita/join.html)了解提交代码的方式。
> 9. **转载须知** :以下所有文章皆为我([程序员Carl](https://github.com/youngyangyang04))的原创。引用本项目文章请注明出处,发现恶意抄袭或搬运,会动用法律武器维护自己的权益。让我们一起维护一个良好的技术创作环境!
@ -51,19 +51,12 @@
## 如何使用该刷题攻略
电脑端还看不到留言,大家可以在公众号[「代码随想录」](https://img-blog.csdnimg.cn/20201124161234338.png),左下角有「刷题攻略」,这是手机版刷题攻略,看完就会发现有很多录友(代码随想录的朋友们)在文章下留言打卡,这份刷题顺序和题解已经陪伴了上万录友了,同时也说明文章的质量是经过上万人的考验!
欢迎每一位学习算法的小伙伴加入到这个学习阵营来!
**目前已经更新了,数组-> 链表-> 哈希表->字符串->栈与队列->树->回溯->贪心,八个专题了,正在讲解动态规划!**
按照先面的排列顺序,从数组开始刷起就可以了,顺序都安排好了,按顺序刷就好。
在刷题攻略中,每个专题开始都有理论基础篇,并不像是教科书般的理论介绍,而是从实战中归纳需要的基础知识。每个专题结束都有总结篇,最这个专题的归纳总结。
如果你是算法老手,这篇攻略也是复习的最佳资料,如果把每个系列对应的总结篇,快速过一遍,整个算法知识体系以及各种解法就重现脑海了。
目前「代码随想录」刷题攻略更新了:**200多篇文章精讲了200道经典算法题目共60w字的详细图解大部分题目都搭配了20分钟左右的视频讲解**,视频质量很好,口碑很好,大家可以去看看,视频列表:[代码随想录视频讲解](https://www.bilibili.com/video/BV1fA4y1o715)。
**这里每一篇题解,都是精品,值得仔细琢磨**。
我在题目讲解中统一使用C++但你会发现下面几乎每篇题解都配有其他语言版本Java、Python、Go、JavaScript等等正是这些[热心小伙们](https://github.com/youngyangyang04/leetcode-master/graphs/contributors)贡献的代码,当然我也会严格把控代码质量。
@ -100,14 +93,11 @@
* [程序员应该用什么用具来写文档?](./problems/前序/程序员写文档工具.md)
* 求职
* [ACM模式练习网站卡码网](https://kamacoder.com/)
* [程序员的简历应该这么写!!(附简历模板)](./problems/前序/程序员简历.md)
* [【专业技能】应该这样写!](https://programmercarl.com/other/jianlizhuanye.html)
* [【项目经历】应该这样写!](https://programmercarl.com/other/jianlixiangmu.html)
* [BAT级别技术面试流程和注意事项都在这里了](./problems/前序/BAT级别技术面试流程和注意事项都在这里了.md)
* [北京有这些互联网公司,你都知道么?](./problems/前序/北京互联网公司总结.md)
* [上海有这些互联网公司,你都知道么?](./problems/前序/上海互联网公司总结.md)
* [深圳有这些互联网公司,你都知道么?](./problems/前序/深圳互联网公司总结.md)
* [广州有这些互联网公司,你都知道么?](./problems/前序/广州互联网公司总结.md)
* [成都有这些互联网公司,你都知道么?](./problems/前序/成都互联网公司总结.md)
* [杭州有这些互联网公司,你都知道么?](./problems/前序/杭州互联网公司总结.md)
* 算法性能分析
* [关于时间复杂度,你不知道的都在这里!](./problems/前序/关于时间复杂度,你不知道的都在这里!.md)
@ -506,7 +496,7 @@
# 关于作者
大家好我是程序员Carl哈工大师兄《代码随想录》作者先后在腾讯和百度从事后端技术研发CSDN博客专家。对算法和C++后端技术有一定的见解利用工作之余重新刷leetcode。
大家好我是程序员Carl哈工大师兄《代码随想录》作者先后在腾讯和百度从事后端技术研发。对算法和C++后端技术有一定的见解利用工作之余重新刷leetcode。
加入「代码随想录」刷题小分队(微信群),可以扫下方二维码,加代码随想录客服微信。
@ -527,4 +517,3 @@
<div align="center"><img src="https://code-thinking-1253855093.file.myqcloud.com/pics/20211026122841.png" data-img="1" width="650" height="500"></img></div>
<!-- 24. [贪心算法714.买卖股票的最佳时机含手续费](./problems/0714.买卖股票的最佳时机含手续费.md) -->

View File

@ -163,7 +163,7 @@ class Solution:
for index, value in enumerate(nums):
if target - value in records: # 遍历当前元素并在map中寻找是否有匹配的key
return [records[target- value], index]
records[value] = index # 遍历当前元素并在map中寻找是否有匹配的key
records[value] = index # 如果没找到匹配对就把访问过的元素和下标加入到map中
return []
```
(版本二)使用集合
@ -318,7 +318,7 @@ function twoSum(nums: number[], target: number): number[] {
};
```
### php:
### PhP:
```php
function twoSum(array $nums, int $target): array
@ -501,3 +501,4 @@ int* twoSum(int* nums, int numsSize, int target, int* returnSize){
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -30,17 +30,17 @@
* 输出:"a"
# 思路
## 思路
本题和[647.回文子串](https://programmercarl.com/0647.回文子串.html) 差不多是一样的但647.回文子串更基本一点建议可以先做647.回文子串
## 暴力解法
### 暴力解法
两层for循环遍历区间起始位置和终止位置然后判断这个区间是不是回文。
时间复杂度O(n^3)
## 动态规划
### 动态规划
动规五部曲:
@ -208,7 +208,7 @@ public:
* 时间复杂度O(n^2)
* 空间复杂度O(n^2)
## 双指针
### 双指针
动态规划的空间复杂度是偏高的,我们再看一下双指针法。
@ -258,9 +258,9 @@ public:
# 其他语言版本
## 其他语言版本
Java
### Java
```java
// 双指针 动态规划
@ -327,7 +327,7 @@ class Solution {
}
```
Python
### Python
```python
class Solution:
@ -377,7 +377,7 @@ class Solution:
return s[start:end]
```
Go
### Go
```go
func longestPalindrome(s string) string {
@ -411,7 +411,7 @@ func longestPalindrome(s string) string {
```
JavaScript
### JavaScript
```js
//动态规划解法
@ -527,7 +527,7 @@ var longestPalindrome = function(s) {
};
```
C
### C
动态规划:
```c
@ -615,7 +615,7 @@ char * longestPalindrome(char * s){
}
```
C#
### C#
動態規則:
```c#
@ -681,3 +681,4 @@ public class Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -21,12 +21,12 @@
说明:尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[还得用回溯算法!| LeetCode17.电话号码的字母组合](https://www.bilibili.com/video/BV1yV4y1V7Ug),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[还得用回溯算法!| LeetCode17.电话号码的字母组合](https://www.bilibili.com/video/BV1yV4y1V7Ug),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
从示例上来说,输入"23"最直接的想法就是两层for循环遍历了吧正好把组合的情况都输出了。
@ -40,7 +40,7 @@
2. 两个字母就两个for循环三个字符我就三个for循环以此类推然后发现代码根本写不出来
3. 输入1 * #按键等等异常情况
## 数字和字母如何映射
### 数字和字母如何映射
可以使用map或者定义一个二维数组例如string letterMap[10],来做映射,我这里定义一个二维数组,代码如下:
@ -59,7 +59,7 @@ const string letterMap[10] = {
};
```
## 回溯法来解决n个for循环的问题
### 回溯法来解决n个for循环的问题
对于回溯法还不了解的同学看这篇:[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)
@ -134,9 +134,6 @@ for (int i = 0; i < letters.size(); i++) {
**但是要知道会有这些异常,如果是现场面试中,一定要考虑到!**
## C++代码
关键地方都讲完了,按照[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)中的回溯法模板不难写出如下C++代码:
@ -233,7 +230,7 @@ public:
所以大家可以按照版本一来写就可以了。
# 总结
## 总结
本篇将题目的三个要点一一列出,并重点强调了和前面讲解过的[77. 组合](https://programmercarl.com/0077.组合.html)和[216.组合总和III](https://programmercarl.com/0216.组合总和III.html)的区别,本题是多个集合求组合,所以在回溯的搜索过程中,都有一些细节需要注意的。
@ -241,10 +238,10 @@ public:
# 其他语言版本
## 其他语言版本
## Java
### Java
```Java
class Solution {
@ -286,7 +283,7 @@ class Solution {
}
```
## Python
### Python
回溯
```python
class Solution:
@ -435,7 +432,7 @@ class Solution:
## Go
### Go
主要在于递归中传递下一个数字
@ -470,7 +467,7 @@ func dfs(digits string, start int) {
}
```
## javaScript
### JavaScript
```js
var letterCombinations = function(digits) {
@ -497,7 +494,7 @@ var letterCombinations = function(digits) {
};
```
## TypeScript
### TypeScript
```typescript
function letterCombinations(digits: string): string[] {
@ -531,7 +528,7 @@ function letterCombinations(digits: string): string[] {
};
```
## Rust
### Rust
```Rust
const map: [&str; 10] = [
@ -563,7 +560,7 @@ impl Solution {
}
```
## C
### C
```c
char* path;
@ -625,7 +622,7 @@ char ** letterCombinations(char * digits, int* returnSize){
}
```
## Swift
### Swift
```swift
func letterCombinations(_ digits: String) -> [String] {
@ -666,7 +663,7 @@ func letterCombinations(_ digits: String) -> [String] {
}
```
## Scala:
### Scala
```scala
object Solution {
@ -702,3 +699,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -152,10 +152,10 @@ public:
## 相关题目推荐
* 26.删除排序数组中的重复项
* 283.移动零
* 844.比较含退格的字符串
* 977.有序数组的平方
* [26.删除排序数组中的重复项](https://leetcode.cn/problems/remove-duplicates-from-sorted-array/)
* [283.移动零](https://leetcode.cn/problems/move-zeroes/)
* [844.比较含退格的字符串](https://leetcode.cn/problems/backspace-string-compare/)
* [977.有序数组的平方](https://leetcode.cn/problems/squares-of-a-sorted-array/)
## 其他语言版本
@ -444,3 +444,4 @@ public class Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -34,7 +34,7 @@
* 输出:[1]
# 思路
## 思路
一些同学可能手动写排列的顺序都没有写对那么写程序的话思路一定是有问题的了我这里以1234为例子把全排列都列出来。可以参考一下规律所在
@ -92,9 +92,9 @@ public:
};
```
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
class Solution {
@ -159,7 +159,7 @@ class Solution {
}
```
## Python
### Python
>直接使用sorted()会开辟新的空间并返回一个新的list故补充一个原地反转函数
```python
class Solution:
@ -191,7 +191,7 @@ class Solution:
"""
```
## Go
### Go
```go
//卡尔的解法
@ -216,7 +216,7 @@ func reverse(a []int,begin,end int){
}
```
## JavaScript
### JavaScript
```js
//卡尔的解法(吐槽一下JavaScript的sort和其他语言的不太一样只想到了拷贝数组去排序再替换原数组来实现nums的[i + 1, nums.length)升序排序)
@ -272,3 +272,4 @@ var nextPermutation = function(nums) {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -6,8 +6,7 @@
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
如果对回溯法理论还不清楚的同学,可以先看这个视频[视频来了!!带你学透回溯算法(理论篇)](https://mp.weixin.qq.com/s/wDd5azGIYWjbU0fdua_qBg)
> 如果对回溯法理论还不清楚的同学,可以先看这个视频[视频来了!!带你学透回溯算法(理论篇)](https://mp.weixin.qq.com/s/wDd5azGIYWjbU0fdua_qBg)
# 37. 解数独
@ -35,11 +34,9 @@
* 你可以假设给定的数独只有唯一解。
* 给定数独永远是 9x9 形式的。
# 算法公开课
**《代码随想录》算法视频公开课:[回溯算法二维递归?解数独不过如此!| LeetCode37. 解数独](https://www.bilibili.com/video/BV1TW4y1471V/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 算法公开课
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[回溯算法二维递归?解数独不过如此!| LeetCode37. 解数独](https://www.bilibili.com/video/BV1TW4y1471V/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -764,3 +761,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -39,11 +39,11 @@ candidates 中的数字可以无限制重复被选取。
[3,5]
]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[Leetcode:39. 组合总和讲解](https://www.bilibili.com/video/BV1KT4y1M7HJ),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[Leetcode:39. 组合总和讲解](https://www.bilibili.com/video/BV1KT4y1M7HJ),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
题目中的**无限制重复被选取,吓得我赶紧想想 出现0 可咋办**然后看到下面提示1 <= candidates[i] <= 200我就放心了。
@ -57,7 +57,7 @@ candidates 中的数字可以无限制重复被选取。
而在[77.组合](https://programmercarl.com/0077.组合.html)和[216.组合总和III](https://programmercarl.com/0216.组合总和III.html) 中都可以知道要递归K层因为要取k个元素的组合。
## 回溯三部曲
### 回溯三部曲
* 递归函数参数
@ -156,7 +156,7 @@ public:
};
```
## 剪枝优化
### 剪枝优化
在这个树形结构中:
@ -217,7 +217,7 @@ public:
* 时间复杂度: O(n * 2^n),注意这只是复杂度的上界,因为剪枝的存在,真实的时间复杂度远小于此
* 空间复杂度: O(target)
# 总结
## 总结
本题和我们之前讲过的[77.组合](https://programmercarl.com/0077.组合.html)、[216.组合总和III](https://programmercarl.com/0216.组合总和III.html)有两点不同:
@ -238,10 +238,10 @@ public:
# 其他语言版本
## 其他语言版本
## Java
### Java
```Java
// 剪枝优化
@ -271,7 +271,7 @@ class Solution {
}
```
## Python
### Python
回溯(版本一)
@ -311,7 +311,7 @@ class Solution:
for i in range(startIndex, len(candidates)):
if total + candidates[i] > target:
break
continue
total += candidates[i]
path.append(candidates[i])
self.backtracking(candidates, target, total, i, path, result)
@ -370,7 +370,7 @@ class Solution:
```
## Go
### Go
主要在于递归中传递下一个数字
@ -404,7 +404,7 @@ func dfs(candidates []int, start int, target int) {
}
```
## JavaScript
### JavaScript
```js
var combinationSum = function(candidates, target) {
@ -430,7 +430,7 @@ var combinationSum = function(candidates, target) {
};
```
## TypeScript
### TypeScript
```typescript
function combinationSum(candidates: number[], target: number): number[][] {
@ -456,7 +456,7 @@ function combinationSum(candidates: number[], target: number): number[][] {
};
```
## Rust
### Rust
```Rust
impl Solution {
@ -485,7 +485,7 @@ impl Solution {
}
```
## C
### C
```c
int* path;
@ -541,7 +541,7 @@ int** combinationSum(int* candidates, int candidatesSize, int target, int* retur
}
```
## Swift
### Swift
```swift
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
@ -570,7 +570,7 @@ func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
}
```
## Scala
### Scala
```scala
object Solution {
@ -604,3 +604,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -41,13 +41,11 @@ candidates 中的每个数字在每个组合中只能使用一次。
]
```
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[回溯算法中的去重,树层去重树枝去重,你弄清楚了没?| LeetCode:40.组合总和II](https://www.bilibili.com/video/BV12V4y1V73A),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[回溯算法中的去重,树层去重树枝去重,你弄清楚了没?| LeetCode:40.组合总和II](https://www.bilibili.com/video/BV12V4y1V73A),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
这道题目和[39.组合总和](https://programmercarl.com/0039.组合总和.html)如下区别:
@ -86,7 +84,7 @@ candidates 中的每个数字在每个组合中只能使用一次。
可以看到图中,每个节点相对于 [39.组合总和](https://mp.weixin.qq.com/s/FLg8G6EjVcxBjwCbzpACPw)我多加了used数组这个used数组下面会重点介绍。
## 回溯三部曲
### 回溯三部曲
* **递归函数参数**
@ -217,7 +215,7 @@ public:
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
## 补充
### 补充
这里直接用startIndex来去重也是可以的 就不用used数组了。
@ -257,7 +255,7 @@ public:
```
# 总结
## 总结
本题同样是求组合总和但就是因为其数组candidates有重复元素而要求不能有重复的组合所以相对于[39.组合总和](https://programmercarl.com/0039.组合总和.html)难度提升了不少。
@ -265,14 +263,10 @@ public:
所以Carl有必要把去重的这块彻彻底底的给大家讲清楚**就连“树层去重”和“树枝去重”都是我自创的词汇,希望对大家理解有帮助!**
## 其他语言版本
# 其他语言版本
## Java
### Java
**使用标记数组**
```Java
class Solution {
@ -355,7 +349,7 @@ class Solution {
}
```
## Python
### Python
回溯
```python
class Solution:
@ -442,7 +436,7 @@ class Solution:
self.combinationSumHelper(candidates, target - candidates[i], i + 1, path, results)
path.pop()
```
## Go
### Go
主要在于如何在回溯中去重
**使用used数组**
@ -518,7 +512,7 @@ func dfs(candidates []int, start int, target int) {
}
}
```
## javaScript
### JavaScript
```js
/**
@ -588,7 +582,7 @@ var combinationSum2 = function(candidates, target) {
};
```
## TypeScript
### TypeScript
```typescript
function combinationSum2(candidates: number[], target: number): number[][] {
@ -619,7 +613,7 @@ function combinationSum2(candidates: number[], target: number): number[][] {
};
```
## Rust
### Rust
```Rust
impl Solution {
@ -654,7 +648,7 @@ impl Solution {
}
```
## C
### C
```c
int* path;
@ -716,7 +710,7 @@ int** combinationSum2(int* candidates, int candidatesSize, int target, int* retu
}
```
## Swift
### Swift
```swift
func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] {
@ -749,7 +743,7 @@ func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] {
```
## Scala
### Scala
```scala
object Solution {
@ -784,3 +778,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -29,7 +29,7 @@
* 输出9
# 思路
## 思路
接雨水问题在面试中还是常见题目的,有必要好好讲一讲。
@ -39,7 +39,7 @@
* 动态规划
* 单调栈
## 暴力解法
### 暴力解法
本题暴力解法也是也是使用双指针。
@ -137,7 +137,7 @@ public:
力扣后面修改了后台测试数据,所以以上暴力解法超时了。
## 双指针优化
### 双指针优化
在暴力解法中,我们可以看到只要记录左边柱子的最高高度 和 右边柱子的最高高度,就可以计算当前位置的雨水面积,这就是通过列来计算。
@ -184,7 +184,7 @@ public:
};
```
## 单调栈解法
### 单调栈解法
关于单调栈的理论基础,单调栈适合解决什么问题,单调栈的工作过程,大家可以先看这题讲解 [739. 每日温度](https://programmercarl.com/0739.每日温度.html)。
@ -194,7 +194,7 @@ public:
而接雨水这道题目,我们正需要寻找一个元素,右边最大元素以及左边最大元素,来计算雨水面积。
### 准备工作
#### 准备工作
那么本题使用单调栈有如下几个问题:
@ -248,7 +248,7 @@ stack<int> st; // 存着下标,计算的时候用下标对应的柱子高度
明确了如上几点,我们再来看处理逻辑。
### 单调栈处理逻辑
#### 单调栈处理逻辑
以下操作过程其实和 [739. 每日温度](https://programmercarl.com/0739.每日温度.html) 也是一样的,建议先做 [739. 每日温度](https://programmercarl.com/0739.每日温度.html)。
@ -596,7 +596,7 @@ class Solution:
```
### Go
### Go:
```go
func trap(height []int) int {
@ -802,7 +802,7 @@ var trap = function(height) {
};
```
### TypeScript
### TypeScript:
暴力解法:
@ -925,8 +925,108 @@ int trap(int* height, int heightSize) {
* 时间复杂度 O(n)
* 空间复杂度 O(1)
### Rust:
双指针
```rust
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let n = height.len();
let mut max_left = vec![0; height.len()];
let mut max_right = vec![0; height.len()];
max_left.iter_mut().zip(max_right.iter_mut().rev()).enumerate().fold((0, 0), |(lm, rm), (idx, (x, y))| {
let lmax = lm.max(height[idx]);
let rmax = rm.max(height[n - 1 - idx]);
*x = lmax; *y = rmax;
(lmax, rmax)
});
height.iter().enumerate().fold(0, |acc, (idx, x)| {
let h = max_left[idx].min(max_right[idx]);
if h > 0 { h - x + acc } else { acc }
})
}
}
```
单调栈
```rust
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let mut stack = vec![];
let mut ans = 0;
for (right_pos, &right_h) in height.iter().enumerate() {
while !stack.is_empty() && height[*stack.last().unwrap()] <= right_h {
let mid_pos = stack.pop().unwrap();
if !stack.is_empty() {
let left_pos = *stack.last().unwrap();
let left_h = height[left_pos];
let top = std::cmp::min(left_h, right_h);
if top > height[mid_pos] {
ans += (top - height[mid_pos]) * (right_pos - left_pos - 1) as i32;
}
}
}
stack.push(right_pos);
}
ans
}
}
```
Rust
双指针
```rust
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let n = height.len();
let mut max_left = vec![0; height.len()];
let mut max_right = vec![0; height.len()];
max_left.iter_mut().zip(max_right.iter_mut().rev()).enumerate().fold((0, 0), |(lm, rm), (idx, (x, y))| {
let lmax = lm.max(height[idx]);
let rmax = rm.max(height[n - 1 - idx]);
*x = lmax; *y = rmax;
(lmax, rmax)
});
height.iter().enumerate().fold(0, |acc, (idx, x)| {
let h = max_left[idx].min(max_right[idx]);
if h > 0 { h - x + acc } else { acc }
})
}
}
```
单调栈
```rust
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
let mut stack = vec![];
let mut ans = 0;
for (right_pos, &right_h) in height.iter().enumerate() {
while !stack.is_empty() && height[*stack.last().unwrap()] <= right_h {
let mid_pos = stack.pop().unwrap();
if !stack.is_empty() {
let left_pos = *stack.last().unwrap();
let left_h = height[left_pos];
let top = std::cmp::min(left_h, right_h);
if top > height[mid_pos] {
ans += (top - height[mid_pos]) * (right_pos - left_pos - 1) as i32;
}
}
}
stack.push(right_pos);
}
ans
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -25,9 +25,9 @@
说明:
假设你总是可以到达数组的最后一个位置。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法,最少跳几步还得看覆盖范围 | LeetCode 45.跳跃游戏 II](https://www.bilibili.com/video/BV1Y24y1r7XZ),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法,最少跳几步还得看覆盖范围 | LeetCode 45.跳跃游戏 II](https://www.bilibili.com/video/BV1Y24y1r7XZ),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -53,7 +53,7 @@
**图中覆盖范围的意义在于,只要红色的区域,最多两步一定可以到!(不用管具体怎么跳,反正一定可以跳到)**
## 方法一
### 方法一
从图中可以看出来,就是移动下标达到了当前覆盖的最远距离下标时,步数就要加一,来增加覆盖距离。最后的步数就是最少步数。
@ -90,7 +90,7 @@ public:
* 空间复杂度: O(1)
## 方法二
### 方法二
依然是贪心,思路和方法一差不多,代码可以简洁一些。
@ -469,3 +469,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -24,9 +24,9 @@
]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[组合与排列的区别,回溯算法求解的时候,有何不同?| LeetCode46.全排列](https://www.bilibili.com/video/BV19v4y1S79W/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[组合与排列的区别,回溯算法求解的时候,有何不同?| LeetCode46.全排列](https://www.bilibili.com/video/BV19v4y1S79W/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -491,3 +491,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -31,9 +31,9 @@
* 1 <= nums.length <= 8
* -10 <= nums[i] <= 10
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[回溯算法求解全排列,如何去重?| LeetCode47.全排列 II](https://www.bilibili.com/video/BV1R84y1i7Tm/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[回溯算法求解全排列,如何去重?| LeetCode47.全排列 II](https://www.bilibili.com/video/BV1R84y1i7Tm/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -58,7 +58,7 @@
在[46.全排列](https://programmercarl.com/0046.全排列.html)中已经详细讲解了排列问题的写法,在[40.组合总和II](https://programmercarl.com/0040.组合总和II.html) 、[90.子集II](https://programmercarl.com/0090.子集II.html)中详细讲解了去重的写法,所以这次我就不用回溯三部曲分析了,直接给出代码,如下:
## C++代码
```CPP
class Solution {
@ -170,7 +170,7 @@ if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
```
```
其实并不行,一定要加上 `used[i - 1] == false`或者`used[i - 1] == true`,因为 used[i - 1] 要一直是 true 或者一直是false 才可以,而不是 一会是true 一会又是false。 所以这个条件要写上。
@ -179,7 +179,7 @@ if (i > 0 && nums[i] == nums[i - 1]) {
## 其他语言版本
### java
### Java
```java
class Solution {
@ -221,7 +221,7 @@ class Solution {
}
```
### python
Python
```python
class Solution:
@ -526,3 +526,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -28,9 +28,9 @@ n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,
* 输入n = 1
* 输出:[["Q"]]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[这就是传说中的N皇后 回溯算法安排!| LeetCode51.N皇后](https://www.bilibili.com/video/BV1Rd4y1c7Bq/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[这就是传说中的N皇后 回溯算法安排!| LeetCode51.N皇后](https://www.bilibili.com/video/BV1Rd4y1c7Bq/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -864,3 +864,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -43,13 +43,11 @@ n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并
  ".Q.."]
]
# 思路
## 思路
详看:[51.N皇后](https://mp.weixin.qq.com/s/lU_QwCMj6g60nh8m98GAWg) ,基本没有区别
# C++代码
```CPP
class Solution {
private:
@ -100,8 +98,9 @@ public:
};
```
# 其他语言补充
JavaScript
## 其他语言补充
### JavaScript
```javascript
var totalNQueens = function(n) {
let count = 0;
@ -146,7 +145,7 @@ var totalNQueens = function(n) {
};
```
TypeScript
### TypeScript
```typescript
// 0-该格为空1-该格有皇后
@ -199,7 +198,7 @@ function checkValid(chess: GridStatus[][], i: number, j: number, n: number): boo
}
```
C
### C
```c
//path[i]为在i行path[i]列上存在皇后
@ -258,7 +257,8 @@ int totalNQueens(int n){
return answer;
}
```
Java
### Java
```java
class Solution {
int count = 0;

View File

@ -16,11 +16,13 @@
- 输出: 6
- 解释:  连续子数组  [4,-1,2,1] 的和最大,为  6。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法的巧妙需要慢慢体会LeetCode53. 最大子序和](https://www.bilibili.com/video/BV1aY4y1Z7ya),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法的巧妙需要慢慢体会LeetCode53. 最大子序和](https://www.bilibili.com/video/BV1aY4y1Z7ya),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 暴力解法
## 思路
### 暴力解法
暴力解法的思路,第一层 for 就是设置起始位置,第二层 for 循环遍历数组寻找最大值
@ -48,7 +50,7 @@ public:
以上暴力的解法 C++勉强可以过,其他语言就不确定了。
## 贪心解法
### 贪心解法
**贪心贪的是哪里呢?**
@ -104,7 +106,7 @@ public:
当然题目没有说如果数组为空,应该返回什么,所以数组为空的话返回啥都可以了。
## 常见误区
### 常见误区
误区一:
@ -122,7 +124,7 @@ public:
其实并不会,因为还有一个变量 result 一直在更新 最大的连续和只要有更大的连续和出现result 就更新了,那么 result 已经把 4 更新了,后面 连续和变成 3也不会对最后结果有影响。
## 动态规划
### 动态规划
当然本题还可以用动态规划来做,在代码随想录动态规划章节我会详细介绍,如果大家想在想看,可以直接跳转:[动态规划版本详解](https://programmercarl.com/0053.%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F%E5%92%8C%EF%BC%88%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%EF%BC%89.html#%E6%80%9D%E8%B7%AF)

View File

@ -17,7 +17,7 @@
## 算法公开课
**《代码随想录》算法视频公开课:[看起来复杂,其实是简单动态规划 | LeetCode53.最大子序和](https://www.bilibili.com/video/BV19V4y1F7b5),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[看起来复杂,其实是简单动态规划 | LeetCode53.最大子序和](https://www.bilibili.com/video/BV19V4y1F7b5),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -97,8 +97,8 @@ public:
## 其他语言版本
### Java:
Java
```java
/**
* 1.dp[i]代表当前下标对应的最大值
@ -140,7 +140,8 @@ class Solution {
}
```
Python
### Python
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
@ -153,7 +154,8 @@ class Solution:
return result
```
Go
### Go
```Go
// solution
// 1, dp
@ -184,7 +186,7 @@ func max(a,b int) int{
}
```
JavaScript
### JavaScript
```javascript
const maxSubArray = nums => {
@ -203,8 +205,7 @@ const maxSubArray = nums => {
};
```
Scala:
### Scala:
```scala
object Solution {
@ -221,7 +222,7 @@ object Solution {
}
```
TypeScript
### TypeScript
```typescript
function maxSubArray(nums: number[]): number {
@ -244,3 +245,4 @@ function maxSubArray(nums: number[]): number {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -6,7 +6,7 @@
## 54.螺旋矩阵
# 54.螺旋矩阵
[力扣题目链接](https://leetcode.cn/problems/spiral-matrix/)

View File

@ -26,9 +26,9 @@
- 输出: false
- 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 所以你永远不可能到达最后一个位置。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法,怎么跳跃不重要,关键在覆盖范围 | LeetCode55.跳跃游戏](https://www.bilibili.com/video/BV1VG4y1X7kB),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法,怎么跳跃不重要,关键在覆盖范围 | LeetCode55.跳跃游戏](https://www.bilibili.com/video/BV1VG4y1X7kB),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路

View File

@ -22,9 +22,9 @@
* 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
* 注意输入类型已于2019年4月15日更改。 请重置默认代码定义以获取新方法签名。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法合并区间有细节LeetCode56.合并区间](https://www.bilibili.com/video/BV1wx4y157nD),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法合并区间有细节LeetCode56.合并区间](https://www.bilibili.com/video/BV1wx4y157nD),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -341,3 +341,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -688,6 +688,58 @@ public class Solution {
}
```
### Ruby:
```ruby
def generate_matrix(n)
result = Array.new(n) { Array.new(n, 0) }
#循环次数
loop_times = 0
#步长
step = n - 1
val = 1
while loop_times < n / 2
#模拟从左向右
for i in 0..step - 1
#行数不变,列数变
result[loop_times][i+loop_times] = val
val += 1
end
#模拟从上到下
for i in 0..step - 1
#列数不变,行数变
result[i+loop_times][n-loop_times-1] = val
val += 1
end
#模拟从右到左
for i in 0..step - 1
#行数不变,列数变
result[n-loop_times-1][n-loop_times-i-1] = val
val += 1
end
#模拟从下到上
for i in 0..step - 1
#列数不变,行数变
result[n-loop_times-i-1][loop_times] = val
val += 1
end
loop_times += 1
step -= 2
end
#如果是奇数,则填充最后一个元素
result[n/2][n/2] = n**2 if n % 2
return result
end
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

View File

@ -50,9 +50,9 @@
* 1 <= m, n <= 100
* 题目数据保证答案小于等于 2 * 10^9
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划中如何初始化很重要!| LeetCode62.不同路径](https://www.bilibili.com/video/BV1ve4y1x7Eu/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划中如何初始化很重要!| LeetCode62.不同路径](https://www.bilibili.com/video/BV1ve4y1x7Eu/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路

View File

@ -46,9 +46,9 @@
* 1 <= m, n <= 100
* obstacleGrid[i][j] 为 0 或 1
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,这次遇到障碍了| LeetCode63. 不同路径 II](https://www.bilibili.com/video/BV1Ld4y1k7c6/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,这次遇到障碍了| LeetCode63. 不同路径 II](https://www.bilibili.com/video/BV1Ld4y1k7c6/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路

View File

@ -29,9 +29,9 @@
* 1 阶 + 2 阶
* 2 阶 + 1 阶
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[带你学透动态规划-爬楼梯|LeetCode:70.爬楼梯)](https://www.bilibili.com/video/BV17h411h7UH),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[带你学透动态规划-爬楼梯|LeetCode:70.爬楼梯)](https://www.bilibili.com/video/BV17h411h7UH),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -522,3 +522,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -127,8 +127,8 @@ public:
## 其他语言版本
### Java:
Java
```java
class Solution {
public int climbStairs(int n) {
@ -148,7 +148,7 @@ class Solution {
}
```
Python3
### Python3
```python
@ -166,8 +166,8 @@ class Solution:
return dp[n]
```
### Go
Go
```go
func climbStairs(n int) int {
//定义
@ -189,7 +189,8 @@ func climbStairs(n int) int {
}
```
JavaScript:
### JavaScript:
```javascript
var climbStairs = function(n) {
const dp = new Array(n + 1).fill(0);
@ -206,7 +207,7 @@ var climbStairs = function(n) {
};
```
TypeScript
### TypeScript
```typescript
function climbStairs(n: number): number {
@ -226,7 +227,7 @@ function climbStairs(n: number): number {
};
```
Rust:
### Rust:
```rust
impl Solution {
@ -250,4 +251,3 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -40,8 +40,8 @@ exection -> execution (插入 'u')
* 0 <= word1.length, word2.length <= 500
* word1 和 word2 由小写英文字母组成
# 算法公开课
**《代码随想录》算法视频公开课:[动态规划终极绝杀! LeetCode72.编辑距离](https://www.bilibili.com/video/BV1we4y157wB/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 算法公开课
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划终极绝杀! LeetCode72.编辑距离](https://www.bilibili.com/video/BV1we4y157wB/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -227,8 +227,8 @@ public:
## 其他语言版本
### Java
Java
```java
public int minDistance(String word1, String word2) {
int m = word1.length();
@ -256,7 +256,8 @@ public int minDistance(String word1, String word2) {
}
```
Python
### Python
```python
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
@ -274,7 +275,8 @@ class Solution:
return dp[-1][-1]
```
Go
### Go
```Go
func minDistance(word1 string, word2 string) int {
m, n := len(word1), len(word2)
@ -310,8 +312,8 @@ func Min(args ...int) int {
}
```
### Javascript
Javascript
```javascript
const minDistance = (word1, word2) => {
let dp = Array.from(Array(word1.length + 1), () => Array(word2.length+1).fill(0));
@ -338,7 +340,7 @@ const minDistance = (word1, word2) => {
};
```
TypeScript
### TypeScript
```typescript
function minDistance(word1: string, word2: string): number {
@ -373,7 +375,7 @@ function minDistance(word1: string, word2: string): number {
};
```
C
### C
```c
@ -405,3 +407,4 @@ int minDistance(char * word1, char * word2){
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -5,10 +5,6 @@
</a>
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
# 第77题. 组合
[力扣题目链接](https://leetcode.cn/problems/combinations/ )
@ -27,13 +23,12 @@
[1,4],
]
# 算法公开课
## 算法公开课
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[带你学透回溯算法-组合问题对应力扣题目77.组合)](https://www.bilibili.com/video/BV1ti4y1L7cv)[组合问题的剪枝操作](https://www.bilibili.com/video/BV1wi4y157er),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**《代码随想录》算法视频公开课:[带你学透回溯算法-组合问题对应力扣题目77.组合)](https://www.bilibili.com/video/BV1ti4y1L7cv)[组合问题的剪枝操作](https://www.bilibili.com/video/BV1wi4y157er),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
本题是回溯法的经典题目。
@ -108,7 +103,7 @@ for (int i = 1; i <= n; i++) {
在[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)中我们提到了回溯法三部曲,那么我们按照回溯法三部曲开始正式讲解代码了。
## 回溯法三部曲
### 回溯法三部曲
* 递归函数的返回值以及参数
@ -345,13 +340,35 @@ public:
## 其他语言版本
### Java
### Java
未剪枝优化
```java
class Solution {
List<List<Integer>> result= new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}
public void backtracking(int n,int k,int startIndex){
if (path.size() == k){
result.add(new ArrayList<>(path));
return;
}
for (int i =startIndex;i<=n;i++){
path.add(i);
backtracking(n,k,i+1);
path.removeLast();
}
}
}
```
剪枝优化:
```java
class Solution {
List<List<Integer>> result = new ArrayList<>();
@ -451,7 +468,7 @@ func dfs(n int, k int, start int) {
}
```
### javascript
### Javascript
剪枝:
@ -751,3 +768,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -7,8 +7,11 @@
# 77.组合优化
## 算法公开课
**《代码随想录》算法视频公开课:[组合问题的剪枝操作](https://www.bilibili.com/video/BV1wi4y157er),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[组合问题的剪枝操作](https://www.bilibili.com/video/BV1wi4y157er),相信结合视频在看本篇题解,更有助于大家对本题的理解。**
## 思路
在[回溯算法:求组合问题!](https://programmercarl.com/0077.组合.html)中我们通过回溯搜索法解决了n个数中求k个数的组合问题。
@ -46,7 +49,7 @@ public:
};
```
# 剪枝优化
## 剪枝优化
我们说过,回溯法虽然是暴力搜索,但也有时候可以有点剪枝优化一下的。
@ -135,7 +138,7 @@ public:
# 总结
## 总结
本篇我们针对求组合问题的回溯法代码做了剪枝优化,这个优化如果不画图的话,其实不好理解,也不好讲清楚。
@ -143,14 +146,10 @@ public:
**就酱学到了就帮Carl转发一下吧让更多的同学知道这里**
## 其他语言版本
### Java
Java
```java
class Solution {
List<List<Integer>> result = new ArrayList<>();
@ -179,7 +178,8 @@ class Solution {
}
```
Python
### Python
```python
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
@ -199,7 +199,8 @@ class Solution:
```
Go
### Go
```Go
var (
path []int
@ -227,7 +228,7 @@ func dfs(n int, k int, start int) {
}
```
javaScript:
### JavaScript
```js
var combine = function(n, k) {
@ -249,7 +250,7 @@ var combine = function(n, k) {
};
```
TypeScript
### TypeScript
```typescript
function combine(n: number, k: number): number[][] {
@ -270,7 +271,7 @@ function combine(n: number, k: number): number[][] {
};
```
Rust:
### Rust
```Rust
impl Solution {
@ -296,7 +297,7 @@ impl Solution {
}
```
C:
### C
```c
int* path;
@ -351,7 +352,7 @@ int** combine(int n, int k, int* returnSize, int** returnColumnSizes){
}
```
Swift
### Swift
```swift
func combine(_ n: Int, _ k: Int) -> [[Int]] {
@ -381,7 +382,7 @@ func combine(_ n: Int, _ k: Int) -> [[Int]] {
}
```
Scala:
### Scala
```scala
object Solution {
@ -414,3 +415,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -27,12 +27,12 @@
  []
]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[回溯算法解决子集问题,树上节点都是目标集和! | LeetCode78.子集](https://www.bilibili.com/video/BV1U84y1q7Ci),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[回溯算法解决子集问题,树上节点都是目标集和! | LeetCode78.子集](https://www.bilibili.com/video/BV1U84y1q7Ci),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
求子集问题和[77.组合](https://programmercarl.com/0077.组合.html)和[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)又不一样了。
@ -52,7 +52,7 @@
从图中红线部分,可以看出**遍历这个树的时候,把所有节点都记录下来,就是要求的子集集合**。
## 回溯三部曲
### 回溯三部曲
* 递归函数参数
@ -102,8 +102,6 @@ for (int i = startIndex; i < nums.size(); i++) {
}
```
## C++代码
根据[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)给出的回溯算法模板:
```
@ -158,7 +156,7 @@ public:
并不会因为每次递归的下一层就是从i+1开始的。
# 总结
## 总结
相信大家经过了
* 组合问题:
@ -178,10 +176,10 @@ public:
**而组合问题、分割问题是收集树形结构中叶子节点的结果**。
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
class Solution {
List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
@ -205,7 +203,7 @@ class Solution {
}
```
## Python
### Python
```python
class Solution:
def subsets(self, nums):
@ -224,7 +222,7 @@ class Solution:
path.pop()
```
## Go
### Go
```Go
var (
path []int
@ -248,7 +246,7 @@ func dfs(nums []int, start int) {
}
```
## Javascript
### Javascript
```Javascript
var subsets = function(nums) {
@ -267,7 +265,7 @@ var subsets = function(nums) {
};
```
## TypeScript
### TypeScript
```typescript
function subsets(nums: number[]): number[][] {
@ -287,7 +285,7 @@ function subsets(nums: number[]): number[][] {
};
```
## Rust
### Rust
```Rust
impl Solution {
@ -311,7 +309,7 @@ impl Solution {
}
```
## C
### C
```c
int* path;
@ -369,7 +367,7 @@ int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
}
```
## Swift
### Swift
```swift
func subsets(_ nums: [Int]) -> [[Int]] {
@ -392,7 +390,7 @@ func subsets(_ nums: [Int]) -> [[Int]] {
}
```
## Scala
### Scala
思路一: 使用本题解思路
@ -451,3 +449,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -20,7 +20,7 @@
* 1 <= heights.length <=10^5
* 0 <= heights[i] <= 10^4
# 思路
## 思路
本题和[42. 接雨水](https://programmercarl.com/0042.接雨水.html),是遥相呼应的两道题目,建议都要仔细做一做,原理上有很多相同的地方,但细节上又有差异,更可以加深对单调栈的理解!
@ -28,7 +28,7 @@
我们先来看一下暴力解法的解法:
## 暴力解法
### 暴力解法
```CPP
class Solution {
@ -55,7 +55,7 @@ public:
如上代码并不能通过leetcode超时了因为时间复杂度是$O(n^2)$。
## 双指针解法
### 双指针解法
本题双指针的写法整体思路和[42. 接雨水](https://programmercarl.com/0042.接雨水.html)是一致的,但要比[42. 接雨水](https://programmercarl.com/0042.接雨水.html)难一些。
@ -98,7 +98,7 @@ public:
};
```
## 单调栈
### 单调栈
本地单调栈的解法和接雨水的题目是遥相呼应的。
@ -169,7 +169,7 @@ public:
}
};
```
```
细心的录友会发现,我在 height数组上后都加了一个元素0 为什么这么做呢?
@ -229,7 +229,7 @@ public:
## 其他语言版本
Java:
### Java:
暴力解法:
```java
@ -335,7 +335,7 @@ class Solution {
}
```
Python3:
### Python3:
```python
@ -468,7 +468,7 @@ class Solution:
```
Go:
### Go:
> 单调栈
@ -506,7 +506,8 @@ func largestRectangleArea(heights []int) int {
```
JavaScript:
### JavaScript:
```javascript
//双指针 js中运行速度最快
var largestRectangleArea = function(heights) {
@ -581,7 +582,7 @@ var largestRectangleArea = function(heights) {
return maxArea;
};
```
TypeScript
### TypeScript
> 暴力法(会超时):
@ -669,9 +670,119 @@ function largestRectangleArea(heights: number[]): number {
};
```
### Rust:
双指针预处理
```rust
impl Solution {
pub fn largest_rectangle_area(v: Vec<i32>) -> i32 {
let n = v.len();
let mut left_smaller_idx = vec![-1; n];
let mut right_smaller_idx = vec![n as i32; n];
for i in 1..n {
let mut mid = i as i32 - 1;
while mid >= 0 && v[mid as usize] >= v[i] {
mid = left_smaller_idx[mid as usize];
}
left_smaller_idx[i] = mid;
}
for i in (0..n-1).rev() {
let mut mid = i + 1;
while mid < n && v[mid] >= v[i] {
mid = right_smaller_idx[mid] as usize;
}
right_smaller_idx[i] = mid as i32;
}
let mut res = 0;
for (idx, &e) in v.iter().enumerate() {
res = res.max((right_smaller_idx[idx] - left_smaller_idx[idx] - 1) * e);
}
dbg!(res)
}
}
```
单调栈
```rust
impl Solution {
pub fn largest_rectangle_area1(mut v: Vec<i32>) -> i32 {
v.insert(0, 0); // 便于使第一个元素能够有左侧<=它的值
v.push(0); // 便于在结束处理最后一个元素后清空残留在栈中的值
let mut res = 0;
let mut stack = vec![]; // 递增的栈
for (idx, &e) in v.iter().enumerate() {
while !stack.is_empty() && v[*stack.last().unwrap()] > e {
let pos = stack.pop().unwrap();
let prev_pos = *stack.last().unwrap();
let s = (idx - prev_pos - 1) as i32 * v[pos];
res = res.max(s);
}
stack.push(idx);
}
res
}
}
```
Rust
双指针预处理
```rust
impl Solution {
pub fn largest_rectangle_area(v: Vec<i32>) -> i32 {
let n = v.len();
let mut left_smaller_idx = vec![-1; n];
let mut right_smaller_idx = vec![n as i32; n];
for i in 1..n {
let mut mid = i as i32 - 1;
while mid >= 0 && v[mid as usize] >= v[i] {
mid = left_smaller_idx[mid as usize];
}
left_smaller_idx[i] = mid;
}
for i in (0..n-1).rev() {
let mut mid = i + 1;
while mid < n && v[mid] >= v[i] {
mid = right_smaller_idx[mid] as usize;
}
right_smaller_idx[i] = mid as i32;
}
let mut res = 0;
for (idx, &e) in v.iter().enumerate() {
res = res.max((right_smaller_idx[idx] - left_smaller_idx[idx] - 1) * e);
}
dbg!(res)
}
}
```
单调栈
```rust
impl Solution {
pub fn largest_rectangle_area1(mut v: Vec<i32>) -> i32 {
v.insert(0, 0); // 便于使第一个元素能够有左侧<=它的值
v.push(0); // 便于在结束处理最后一个元素后清空残留在栈中的值
let mut res = 0;
let mut stack = vec![]; // 递增的栈
for (idx, &e) in v.iter().enumerate() {
while !stack.is_empty() && v[*stack.last().unwrap()] > e {
let pos = stack.pop().unwrap();
let prev_pos = *stack.last().unwrap();
let s = (idx - prev_pos - 1) as i32 * v[pos];
res = res.max(s);
}
stack.push(idx);
}
res
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -4,7 +4,6 @@
</a>
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
# 90.子集II
[力扣题目链接](https://leetcode.cn/problems/subsets-ii/)
@ -25,9 +24,9 @@
[]
]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[回溯算法解决子集问题,如何去重?| LeetCode90.子集II](https://www.bilibili.com/video/BV1vm4y1F71J/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[回溯算法解决子集问题,如何去重?| LeetCode90.子集II](https://www.bilibili.com/video/BV1vm4y1F71J/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -240,7 +239,7 @@ class Solution {
#### Python3
### Python3
回溯 利用used数组去重
```python
@ -646,3 +645,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -40,16 +40,12 @@
* 0 <= s.length <= 3000
* s 仅由数字组成
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[93.复原IP地址](https://www.bilibili.com/video/BV1XP4y1U73i/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 算法公开课
**《代码随想录》算法视频公开课:[回溯算法如何分割字符串并判断是合法IP| LeetCode93.复原IP地址](https://www.bilibili.com/video/BV1XP4y1U73i/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[回溯算法如何分割字符串并判断是合法IP| LeetCode93.复原IP地址](https://www.bilibili.com/video/BV1XP4y1U73i/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
做这道题目之前,最好先把[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)这个做了。
@ -63,7 +59,7 @@
![93.复原IP地址](https://code-thinking-1253855093.file.myqcloud.com/pics/20201123203735933.png)
## 回溯三部曲
### 回溯三部曲
* 递归参数
@ -134,7 +130,7 @@ for (int i = startIndex; i < s.size(); i++) {
}
```
## 判断子串是否合法
### 判断子串是否合法
最后就是在写一个判断段位是否是有效段位了。
@ -169,8 +165,6 @@ bool isValid(const string& s, int start, int end) {
}
```
## C++代码
根据[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)给出的回溯算法模板:
@ -247,7 +241,7 @@ public:
* 时间复杂度: O(3^4)IP地址最多包含4个数字每个数字最多有3种可能的分割方式则搜索树的最大深度为4每个节点最多有3个子节点。
* 空间复杂度: O(n)
# 总结
## 总结
在[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)中我列举的分割字符串的难点,本题都覆盖了。
@ -259,9 +253,9 @@ public:
# 其他语言版本
## 其他语言版本
## java
### Java
```java
class Solution {
@ -402,7 +396,7 @@ class Solution {
```
## python
### Python
回溯(版本一)
```python
@ -478,9 +472,7 @@ class Solution:
```
## Go
### Go
```go
var (
@ -517,7 +509,7 @@ func dfs(s string, start int) {
}
```
## JavaScript
### JavaScript
```js
/**
@ -547,7 +539,7 @@ var restoreIpAddresses = function(s) {
};
```
## TypeScript
### TypeScript
```typescript
function isValidIpSegment(str: string): boolean {
@ -586,7 +578,7 @@ function restoreIpAddresses(s: string): string[] {
};
```
## Rust
### Rust
```Rust
impl Solution {
@ -643,7 +635,7 @@ impl Solution {
}
```
## C
### C
```c
//记录结果
char** result;
@ -719,7 +711,7 @@ char ** restoreIpAddresses(char * s, int* returnSize){
}
```
## Swift
### Swift
```swift
// 判断区间段是否合法
@ -766,7 +758,7 @@ func restoreIpAddresses(_ s: String) -> [String] {
}
```
## Scala
### Scala
```scala
object Solution {
@ -813,3 +805,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -16,9 +16,9 @@
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210113161941835.png)
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划找到子状态之间的关系很重要!| LeetCode96.不同的二叉搜索树](https://www.bilibili.com/video/BV1eK411o7QA/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划找到子状态之间的关系很重要!| LeetCode96.不同的二叉搜索树](https://www.bilibili.com/video/BV1eK411o7QA/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路

View File

@ -20,18 +20,18 @@
![98.验证二叉搜索树](https://code-thinking-1253855093.file.myqcloud.com/pics/20230310000750.png)
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[你对二叉搜索树了解的还不够! | LeetCode98.验证二叉搜索树](https://www.bilibili.com/video/BV18P411n7Q4),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[你对二叉搜索树了解的还不够! | LeetCode98.验证二叉搜索树](https://www.bilibili.com/video/BV18P411n7Q4),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
要知道中序遍历下,输出的二叉搜索树节点的数值是有序序列。
有了这个特性,**验证二叉搜索树,就相当于变成了判断一个序列是不是递增的了。**
## 递归法
### 递归法
可以递归中序遍历将二叉搜索树转变成一个数组,代码如下:
@ -211,7 +211,7 @@ public:
最后这份代码看上去整洁一些,思路也清晰。
## 迭代法
### 迭代法
可以用迭代法模拟二叉树中序遍历,对前中后序迭代法生疏的同学可以看这两篇[二叉树:听说递归能做的,栈也能做!](https://programmercarl.com/二叉树的迭代遍历.html)[二叉树:前中后序迭代方式统一写法](https://programmercarl.com/二叉树的统一迭代法.html)
@ -245,7 +245,7 @@ public:
在[二叉树:二叉搜索树登场!](https://programmercarl.com/0700.二叉搜索树中的搜索.html)中我们分明写出了痛哭流涕的简洁迭代法,怎么在这里不行了呢,因为本题是要验证二叉搜索树啊。
# 总结
## 总结
这道题目是一个简单题,但对于没接触过的同学还是有难度的。
@ -254,10 +254,10 @@ public:
只要把基本类型的题目都做过,总结过之后,思路自然就开阔了。
# 其他语言版本
## 其他语言版本
## Java
### Java
```Java
//使用統一迭代法
@ -369,7 +369,7 @@ class Solution {
}
```
## Python
### Python
递归法(版本一)利用中序递增性质,转换成数组
```python
@ -479,7 +479,7 @@ class Solution:
```
## Go
### Go
```Go
func isValidBST(root *TreeNode) bool {
@ -526,7 +526,7 @@ func isValidBST(root *TreeNode) bool {
}
```
## JavaScript
### JavaScript
辅助数组解决
@ -595,7 +595,7 @@ var isValidBST = function (root) {
};
```
## TypeScript
### TypeScript
> 辅助数组解决:
@ -637,7 +637,7 @@ function isValidBST(root: TreeNode | null): boolean {
};
```
## Scala
### Scala
辅助数组解决:
```scala
@ -682,7 +682,7 @@ object Solution {
}
```
## rust
### Rust
递归:
@ -735,3 +735,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -19,7 +19,7 @@
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210726173011.png)
# 思路
## 思路
在[101.对称二叉树](https://programmercarl.com/0101.对称二叉树.html)中,我们讲到对于二叉树是否对称,要比较的是根节点的左子树与右子树是不是相互翻转的,理解这一点就知道了**其实我们要比较的是两个树(这两个树是根节点的左右子树)**,所以在递归遍历的过程中,也是要同时遍历两棵树。
@ -115,7 +115,7 @@ public:
当然我可以把如上代码整理如下:
## 递归
### 递归
```CPP
class Solution {
@ -134,7 +134,7 @@ public:
};
```
## 迭代法
### 迭代法
```CPP
class Solution {
@ -166,9 +166,9 @@ public:
};
```
# 其他语言版本
## 其他语言版本
Java
### Java
```java
// 递归法
@ -205,7 +205,8 @@ class Solution {
}
}
```
Python
### Python
```python
# 递归法
class Solution:
@ -236,7 +237,8 @@ class Solution:
que.append(rightNode.right)
return True
```
Go
### Go
> 递归法
```go
func isSameTree(p *TreeNode, q *TreeNode) bool {
@ -258,7 +260,7 @@ func isSameTree(p *TreeNode, q *TreeNode) bool {
}
```
JavaScript
### JavaScript
> 递归法
@ -296,7 +298,7 @@ var isSameTree = (p, q) => {
};
```
TypeScript:
### TypeScript:
> 递归法-先序遍历
@ -341,3 +343,4 @@ function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -29,9 +29,9 @@
![106. 从中序与后序遍历序列构造二叉树1](https://code-thinking-1253855093.file.myqcloud.com/pics/20210203154316774.png)
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[坑很多!来看看你掉过几次坑 | LeetCode106.从中序与后序遍历序列构造二叉树](https://www.bilibili.com/video/BV1vW4y1i7dn),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[坑很多!来看看你掉过几次坑 | LeetCode106.从中序与后序遍历序列构造二叉树](https://www.bilibili.com/video/BV1vW4y1i7dn),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -158,8 +158,6 @@ root->right = traversal(rightInorder, rightPostorder);
完整代码如下:
### C++完整代码
```CPP
class Solution {
private:
@ -281,8 +279,6 @@ public:
下面给出用下标索引写出的代码版本思路是一样的只不过不用重复定义vector了每次用下标索引来分割
### C++优化版本
```CPP
class Solution {
private:
@ -400,8 +396,9 @@ public:
};
```
## 相关题目推荐
# 105.从前序与中序遍历序列构造二叉树
### 105.从前序与中序遍历序列构造二叉树
[力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
@ -418,7 +415,7 @@ public:
![105. 从前序与中序遍历序列构造二叉树](https://code-thinking-1253855093.file.myqcloud.com/pics/20210203154626672.png)
## 思路
### 思路
本题和106是一样的道理。
@ -547,7 +544,7 @@ public:
};
```
# 思考题
## 思考题
前序和中序可以唯一确定一棵二叉树。
@ -569,7 +566,7 @@ tree2 的前序遍历是[1 2 3] 后序遍历是[3 2 1]。
所以前序和后序不能唯一确定一棵二叉树!
# 总结
## 总结
之前我们讲的二叉树题目都是各种遍历二叉树,这次开始构造二叉树了,思路其实比较简单,但是真正代码实现出来并不容易。
@ -585,9 +582,9 @@ tree2 的前序遍历是[1 2 3] 后序遍历是[3 2 1]。
# 其他语言版本
## 其他语言版本
## Java
### Java
106.从中序与后序遍历序列构造二叉树
@ -688,7 +685,7 @@ class Solution {
}
```
## Python
### Python
105.从前序与中序遍历序列构造二叉树
@ -754,7 +751,7 @@ class Solution:
return root
```
## Go
### Go
106 从中序与后序遍历序列构造二叉树
@ -833,9 +830,7 @@ func build(pre []int, in []int, root int, l, r int) *TreeNode {
```
## JavaScript
### JavaScript
```javascript
var buildTree = function(inorder, postorder) {
@ -863,7 +858,7 @@ var buildTree = function(preorder, inorder) {
};
```
## TypeScript
### TypeScript
> 106.从中序与后序遍历序列构造二叉树
@ -969,7 +964,7 @@ function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
};
```
## C
### C
106 从中序与后序遍历序列构造二叉树
@ -1047,7 +1042,7 @@ struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int in
}
```
## Swift
### Swift
105 从前序与中序遍历序列构造二叉树
@ -1140,7 +1135,7 @@ class Solution_0106 {
}
```
## Scala
### Scala
106 从中序与后序遍历序列构造二叉树
@ -1188,7 +1183,7 @@ object Solution {
}
```
## rust
### Rust
106 从中序与后序遍历序列构造二叉树
@ -1238,3 +1233,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -20,11 +20,11 @@
![108.将有序数组转换为二叉搜索树](https://code-thinking-1253855093.file.myqcloud.com/pics/20201022164420763.png)
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[构造平衡二叉搜索树!| LeetCode108.将有序数组转换为二叉搜索树](https://www.bilibili.com/video/BV1uR4y1X7qL?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[构造平衡二叉搜索树!| LeetCode108.将有序数组转换为二叉搜索树](https://www.bilibili.com/video/BV1uR4y1X7qL?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
做这道题目之前大家可以了解一下这几道:
@ -71,7 +71,7 @@
**这也是题目中强调答案不是唯一的原因。 理解这一点,这道题目算是理解到位了**。
## 递归
### 递归
递归三部曲:
@ -155,7 +155,7 @@ public:
**注意在调用traversal的时候传入的left和right为什么是0和nums.size() - 1因为定义的区间为左闭右闭**。
## 迭代法
### 迭代法
迭代法可以通过三个队列来模拟,一个队列放遍历的节点,一个队列放左区间下标,一个队列放右区间下标。
@ -203,7 +203,7 @@ public:
};
```
# 总结
## 总结
**在[二叉树:构造二叉树登场!](https://programmercarl.com/0106.从中序与后序遍历序列构造二叉树.html) 和 [二叉树:构造一棵最大的二叉树](https://programmercarl.com/0654.最大二叉树.html)之后,我们顺理成章的应该构造一下二叉搜索树了,一不小心还是一棵平衡二叉搜索树**。
@ -216,10 +216,10 @@ public:
最后依然给出迭代的方法,其实就是模拟取中间元素,然后不断分割去构造二叉树的过程。
# 其他语言版本
## 其他语言版本
## Java
### Java
递归: 左闭右开 [left,right)
```Java
@ -315,7 +315,7 @@ class Solution {
}
```
## Python
### Python
递归法
```python
class Solution:
@ -377,7 +377,7 @@ class Solution:
```
## Go
### Go
递归(隐含回溯)
@ -396,7 +396,7 @@ func sortedArrayToBST(nums []int) *TreeNode {
}
```
## JavaScript
### JavaScript
递归
```javascript
@ -453,7 +453,7 @@ var sortedArrayToBST = function(nums) {
return root;
};
```
## TypeScript
### TypeScript
```typescript
function sortedArrayToBST(nums: number[]): TreeNode | null {
@ -469,7 +469,7 @@ function sortedArrayToBST(nums: number[]): TreeNode | null {
};
```
## C
### C
递归
```c
@ -490,7 +490,7 @@ struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
}
```
## Scala
### Scala
递归:
@ -511,7 +511,7 @@ object Solution {
}
```
## rust
### Rust
递归:
@ -536,3 +536,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -21,9 +21,9 @@
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
## 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[拿不准的遍历顺序,搞不清的回溯过程,我太难了! | LeetCode112. 路径总和](https://www.bilibili.com/video/BV19t4y1L7CR),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[拿不准的遍历顺序,搞不清的回溯过程,我太难了! | LeetCode112. 路径总和](https://www.bilibili.com/video/BV19t4y1L7CR),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -32,8 +32,8 @@
那么接下来我通过详细讲解如下两道题,来回答这个问题:
* 112.路径总和
* 113.路径总和ii
* [112.路径总和](https://leetcode.cn/problems/path-sum/)
* [113.路径总和ii](https://leetcode.cn/problems/path-sum-ii/)
这道题我们要遍历从根节点到叶子节点的路径看看总和是不是目标和。
@ -218,7 +218,9 @@ public:
如果大家完全理解了本题的递归方法之后就可以顺便把leetcode上113. 路径总和ii做了。
# 113. 路径总和ii
## 相关题目推荐
### 113. 路径总和ii
[力扣题目链接](https://leetcode.cn/problems/path-sum-ii/)
@ -232,7 +234,7 @@ public:
![113.路径总和ii1.png](https://code-thinking-1253855093.file.myqcloud.com/pics/20210203160854654.png)
## 思路
### 思路
113.路径总和ii要遍历整个树找到所有路径**所以递归函数不要返回值!**
@ -289,7 +291,7 @@ public:
至于113. 路径总和ii 的迭代法我并没有写,用迭代方式记录所有路径比较麻烦,也没有必要,如果大家感兴趣的话,可以再深入研究研究。
## 总结
### 总结
本篇通过leetcode上112. 路径总和 和 113. 路径总和ii 详细的讲解了 递归函数什么时候需要返回值,什么不需要返回值。
@ -300,11 +302,11 @@ public:
# 其他语言版本
## 其他语言版本
## java
### Java
### 0112.路径总和
0112.路径总和
```java
class solution {
@ -422,7 +424,7 @@ class solution {
}
```
### 0113.路径总和-ii
0113.路径总和-ii
```java
class solution {
@ -529,9 +531,9 @@ class Solution {
}
```
## python
### Python
### 0112.路径总和
0112.路径总和
(版本一) 递归
```python
@ -618,7 +620,7 @@ class Solution:
### 0113.路径总和-ii
0113.路径总和-ii
(版本一) 递归
```python
@ -719,9 +721,9 @@ class Solution:
```
## go
### Go
### 112. 路径总和
112. 路径总和
```go
//递归法
@ -746,7 +748,7 @@ func hasPathSum(root *TreeNode, targetSum int) bool {
}
```
### 113. 路径总和 II
113. 路径总和 II
```go
/**
@ -786,9 +788,9 @@ func traverse(node *TreeNode, result *[][]int, currPath *[]int, targetSum int) {
}
```
## javascript
### Javascript
### 0112.路径总和
0112.路径总和
**递归**
@ -852,7 +854,7 @@ let hasPathSum = function(root, targetSum) {
};
```
### 0113.路径总和-ii
0113.路径总和-ii
**递归**
@ -950,9 +952,9 @@ let pathSum = function(root, targetSum) {
};
```
## TypeScript
### TypeScript
### 0112.路径总和
0112.路径总和
**递归法:**
@ -1034,7 +1036,7 @@ function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
};
```
### 0112.路径总和 ii
0112.路径总和 ii
**递归法:**
@ -1070,9 +1072,9 @@ function pathSum(root: TreeNode | null, targetSum: number): number[][] {
};
```
## Swift
### Swift
### 0112.路径总和
0112.路径总和
**递归**
@ -1141,7 +1143,7 @@ func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool {
}
```
### 0113.路径总和 II
0113.路径总和 II
**递归**
@ -1192,10 +1194,11 @@ func traversal(_ cur: TreeNode?, count: Int) {
}
```
## C
### C
> 0112.路径总和
> 递归法:
0112.路径总和
递归法:
```c
bool hasPathSum(struct TreeNode* root, int targetSum){
@ -1252,7 +1255,7 @@ bool hasPathSum(struct TreeNode* root, int targetSum){
}
```
> 0113.路径总和 II
0113.路径总和 II
```c
int** ret;
@ -1317,9 +1320,9 @@ int** pathSum(struct TreeNode* root, int targetSum, int* returnSize, int** retur
}
```
## Scala
### Scala
### 0112.路径总和
0112.路径总和
**递归:**
@ -1369,7 +1372,7 @@ object Solution {
}
```
### 0113.路径总和 II
0113.路径总和 II
**递归:**
@ -1405,9 +1408,9 @@ object Solution {
}
```
## rust
### Rust
### 112.路径总和.md
0112.路径总和
递归:
@ -1461,7 +1464,7 @@ impl Solution {
}
```
### 113.路径总和-ii
0113.路径总和-ii
```rust
impl Solution {

View File

@ -157,8 +157,8 @@ public:
## 其他语言版本
### Java
Java
```java
class Solution {
public int numDistinct(String s, String t) {
@ -182,7 +182,8 @@ class Solution {
}
```
Python
### Python
```python
class Solution:
def numDistinct(self, s: str, t: str) -> int:
@ -200,7 +201,8 @@ class Solution:
return dp[-1][-1]
```
Python3:
### Python3:
```python
class SolutionDP2:
"""
@ -234,7 +236,8 @@ class SolutionDP2:
return dp[-1]
```
Go
### Go
```go
func numDistinct(s string, t string) int {
dp:= make([][]int,len(s)+1)
@ -259,8 +262,8 @@ func numDistinct(s string, t string) int {
}
```
### Javascript:
Javascript:
```javascript
const numDistinct = (s, t) => {
let dp = Array.from(Array(s.length + 1), () => Array(t.length +1).fill(0));
@ -283,7 +286,7 @@ const numDistinct = (s, t) => {
};
```
TypeScript
### TypeScript
```typescript
function numDistinct(s: string, t: string): number {
@ -311,7 +314,7 @@ function numDistinct(s: string, t: string): number {
};
```
Rust:
### Rust:
```rust
impl Solution {
@ -368,7 +371,9 @@ impl Solution {
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -30,7 +30,7 @@ struct Node {
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210727143202.png)
# 思路
## 思路
注意题目提示内容,:
* 你只能使用常量级额外空间。
@ -38,7 +38,7 @@ struct Node {
基本上就是要求使用递归了,迭代的方式一定会用到栈或者队列。
## 递归
### 递归
一想用递归怎么做呢,虽然层序遍历是最直观的,但是递归的方式确实不好想。
@ -83,7 +83,7 @@ public:
};
```
## 迭代(层序遍历)
### 迭代(层序遍历)
本题使用层序遍历是最为直观的,如果对层序遍历不了解,看这篇:[二叉树:层序遍历登场!](https://programmercarl.com/0102.二叉树的层序遍历.html)。
@ -114,9 +114,9 @@ public:
};
```
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
// 递归法
@ -169,7 +169,7 @@ class Solution {
}
```
## Python
### Python
```python
# 递归法
@ -210,7 +210,7 @@ class Solution:
nodePre.next = None # 本层最后一个节点指向None
return root
```
## Go
### Go
```go
// 迭代法
func connect(root *Node) *Node {
@ -259,7 +259,7 @@ func connect(root *Node) *Node {
}
```
## JavaScript
### JavaScript
```js
const connect = root => {
@ -287,7 +287,7 @@ const connect = root => {
};
```
## TypeScript
### TypeScript
命名空间Node与typescript中内置类型冲突这里改成了NodePro
@ -365,3 +365,4 @@ function connect(root: NodePro | null): NodePro | null {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -24,11 +24,9 @@
* 输出0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
# 算法公开课
**《代码随想录》算法视频公开课:[动态规划之 LeetCode121.买卖股票的最佳时机1](https://www.bilibili.com/video/BV1Xe4y1u77q),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 算法公开课
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划之 LeetCode121.买卖股票的最佳时机1](https://www.bilibili.com/video/BV1Xe4y1u77q),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -202,7 +200,7 @@ public:
## 其他语言版本
Java:
### Java:
> 贪心法:
@ -294,8 +292,7 @@ class Solution {
```
Python:
### Python:
> 贪心法:
```python
@ -351,7 +348,8 @@ class Solution:
return dp1
```
Go:
### Go:
> 贪心法:
```Go
func maxProfit(prices []int) int {
@ -418,7 +416,7 @@ func max(a, b int) int {
}
```
JavaScript:
### JavaScript:
> 动态规划
@ -454,7 +452,7 @@ var maxProfit = function(prices) {
};
```
TypeScript
### TypeScript
> 贪心法
@ -492,7 +490,7 @@ function maxProfit(prices: number[]): number {
};
```
C#
### C#
> 贪心法
@ -533,7 +531,7 @@ public class Solution
}
```
Rust:
### Rust:
> 贪心

View File

@ -37,9 +37,9 @@
- 1 <= prices.length <= 3 \* 10 ^ 4
- 0 <= prices[i] <= 10 ^ 4
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法也能解决股票问题LeetCode122.买卖股票最佳时机 II](https://www.bilibili.com/video/BV1ev4y1C7na),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法也能解决股票问题LeetCode122.买卖股票最佳时机 II](https://www.bilibili.com/video/BV1ev4y1C7na),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -316,7 +316,7 @@ function maxProfit(prices: number[]): number {
}
```
### Rust
### Rust
贪心:
@ -389,7 +389,7 @@ int maxProfit(int* prices, int pricesSize){
}
```
### Scala
### Scala
贪心:
@ -411,3 +411,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -34,9 +34,9 @@
* 1 <= prices.length <= 3 * 10 ^ 4
* 0 <= prices[i] <= 10 ^ 4
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,股票问题第二弹 | LeetCode122.买卖股票的最佳时机II](https://www.bilibili.com/video/BV1D24y1Q7Ls),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,股票问题第二弹 | LeetCode122.买卖股票的最佳时机II](https://www.bilibili.com/video/BV1D24y1Q7Ls),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -133,8 +133,8 @@ public:
## 其他语言版本
### Java
Java
```java
// 动态规划
class Solution
@ -191,7 +191,7 @@ class Solution {
}
```
Python
### Python
> 版本一:
```python
@ -221,7 +221,8 @@ class Solution:
return dp[(length-1) % 2][1]
```
Go
### Go
```go
// 买卖股票的最佳时机Ⅱ 动态规划
// 时间复杂度O(n) 空间复杂度O(n)
@ -250,7 +251,8 @@ func max(a, b int) int {
}
```
Javascript
### JavaScript
```javascript
// 方法一动态规划dp 数组)
const maxProfit = (prices) => {
@ -290,7 +292,7 @@ const maxProfit = (prices) => {
}
```
TypeScript
### TypeScript
> 动态规划
@ -326,7 +328,7 @@ function maxProfit(prices: number[]): number {
};
```
C#
### C#
> 贪心法
@ -363,7 +365,7 @@ public class Solution
}
```
Rust:
### Rust:
> 贪心
@ -414,4 +416,3 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -39,9 +39,9 @@
* 1 <= prices.length <= 10^5
* 0 <= prices[i] <= 10^5
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,股票至多买卖两次,怎么求? | LeetCode123.买卖股票最佳时机III](https://www.bilibili.com/video/BV1WG411K7AR),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,股票至多买卖两次,怎么求? | LeetCode123.买卖股票最佳时机III](https://www.bilibili.com/video/BV1WG411K7AR),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -221,7 +221,7 @@ public:
## 其他语言版本
Java:
### Java:
```java
// 版本一
@ -277,7 +277,7 @@ class Solution {
}
```
Python:
### Python:
> 版本一:
```python
@ -314,7 +314,7 @@ class Solution:
return dp[4]
```
Go:
### Go:
```go
func maxProfit(prices []int) int {
@ -344,7 +344,7 @@ func max(a, b int) int {
}
```
JavaScript:
### JavaScript:
> 版本一:
@ -383,7 +383,7 @@ const maxProfit = prices => {
};
```
TypeScript
### TypeScript
> 版本一
@ -413,7 +413,7 @@ function maxProfit(prices: number[]): number {
};
```
Rust
### Rust
> 版本一
@ -465,3 +465,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -29,7 +29,7 @@
* 解释endWord "cog" 不在字典中,所以无法进行转换。
# 思路
## 思路
以示例1为例从这个图中可以看出 hit 到 cog的路线不止一条有三条一条是最短的长度为5两条长度为6。
@ -97,9 +97,9 @@ public:
当然本题也可以用双向BFS就是从头尾两端进行搜索大家感兴趣可以自己去实现这里就不再做详细讲解了。
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
@ -196,7 +196,7 @@ class Solution {
}
```
## Python
### Python
```
class Solution:
@ -221,7 +221,7 @@ class Solution:
queue.append(newWord)
return 0
```
## Go
### Go
```go
func ladderLength(beginWord string, endWord string, wordList []string) int {
wordMap, que, depth := getWordMap(wordList, beginWord), []string{beginWord}, 0
@ -274,7 +274,7 @@ func getCandidates(word string) []string {
}
```
## JavaScript
### JavaScript
```javascript
var ladderLength = function(beginWord, endWord, wordList) {
// 将wordList转成Set提高查询速度
@ -310,7 +310,7 @@ var ladderLength = function(beginWord, endWord, wordList) {
};
```
## TypeScript
### TypeScript
```typescript
function ladderLength(
beginWord: string,
@ -364,4 +364,3 @@ function diffonechar(word1: string, word2: string): boolean {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -10,7 +10,7 @@
[力扣题目链接](https://leetcode.cn/problems/sum-root-to-leaf-numbers/)
# 思路
## 思路
本题和[113.路径总和II](https://programmercarl.com/0112.路径总和.html#_113-路径总和ii)是类似的思路,做完这道题,可以顺便把[113.路径总和II](https://programmercarl.com/0112.路径总和.html#_113-路径总和ii) 和 [112.路径总和](https://programmercarl.com/0112.路径总和.html#_112-路径总和) 做了。
@ -24,7 +24,7 @@
那么先按递归三部曲来分析:
## 递归三部曲
### 递归三部曲
如果对递归三部曲不了解的话,可以看这里:[二叉树:前中后递归详解](https://programmercarl.com/二叉树的递归遍历.html)
@ -116,7 +116,7 @@ path.pop_back(); // 回溯
```
**把回溯放在花括号外面了,世界上最遥远的距离,是你在花括号里,而我在花括号外!** 这就不对了。
## 整体C++代码
整体C++代码
关键逻辑分析完了整体C++代码如下:
@ -162,16 +162,16 @@ public:
};
```
# 总结
## 总结
过于简洁的代码,很容易让初学者忽视了本题中回溯的精髓,甚至作者本身都没有想清楚自己用了回溯。
**我这里提供的代码把整个回溯过程充分体现出来,希望可以帮助大家看的明明白白!**
# 其他语言版本
## 其他语言版本
Java
### Java
```java
class Solution {
@ -219,7 +219,8 @@ class Solution {
}
```
Python
### Python
```python
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
@ -246,7 +247,7 @@ class Solution:
backtrace(root)
return res
```
Go
### Go
```go
func sumNumbers(root *TreeNode) int {
@ -271,7 +272,8 @@ func dfs(root *TreeNode, tmpSum int, sum *int) {
JavaScript
### JavaScript
```javascript
var sumNumbers = function(root) {
const listToInt = path => {
@ -315,7 +317,7 @@ var sumNumbers = function(root) {
};
```
TypeScript
### TypeScript
```typescript
function sumNumbers(root: TreeNode | null): number {
@ -351,7 +353,7 @@ function sumNumbers(root: TreeNode | null): number {
};
```
C:
### C:
```c
//sum记录总和
@ -384,3 +386,4 @@ int sumNumbers(struct TreeNode* root){
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -23,12 +23,12 @@
["a","a","b"]
]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[131.分割回文串](https://www.bilibili.com/video/BV1c54y1e7k6),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[131.分割回文串](https://www.bilibili.com/video/BV1c54y1e7k6),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
本题这涉及到两个关键问题:
@ -58,7 +58,7 @@
此时可以发现,切割问题的回溯搜索的过程和组合问题的回溯搜索的过程是差不多的。
## 回溯三部曲
### 回溯三部曲
* 递归函数参数
@ -124,7 +124,7 @@ for (int i = startIndex; i < s.size(); i++) {
**注意切割过的位置不能重复切割所以backtracking(s, i + 1); 传入下一层的起始位置为i + 1**。
## 判断回文子串
### 判断回文子串
最后我们看一下回文子串要如何判断了,判断一个字符串是否是回文。
@ -147,8 +147,6 @@ for (int i = startIndex; i < s.size(); i++) {
此时关键代码已经讲解完毕,整体代码如下(详细注释了)
## C++整体代码
根据Carl给出的回溯算法模板
```CPP
@ -212,7 +210,7 @@ public:
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n^2)
# 优化
## 优化
上面的代码还存在一定的优化空间, 在于如何更高效的计算一个子字符串是否是回文字串。上述代码```isPalindrome```函数运用双指针的方法来判定对于一个字符串```s```, 给定起始下标和终止下标, 截取出的子字符串是否是回文字串。但是其中有一定的重复计算存在:
@ -272,7 +270,7 @@ public:
```
# 总结
## 总结
这道题目在leetcode上是中等但可以说是hard的题目了但是代码其实就是按照模板的样子来的。
@ -306,10 +304,10 @@ public:
# 其他语言版本
## 其他语言版本
## Java
### Java
```Java
class Solution {
List<List<String>> lists = new ArrayList<>();
@ -351,7 +349,7 @@ class Solution {
}
```
## Python
### Python
回溯 基本版
```python
class Solution:
@ -473,7 +471,7 @@ class Solution:
return all(s[i] == s[len(s) - 1 - i] for i in range(len(s) // 2))
```
## Go
### Go
```go
var (
path []string // 放已经回文的子串
@ -512,7 +510,7 @@ func isPalindrome(s string) bool {
}
```
## javaScript
### JavaScript
```js
/**
@ -545,7 +543,7 @@ var partition = function(s) {
};
```
## TypeScript
### TypeScript
```typescript
function partition(s: string): string[][] {
@ -582,7 +580,7 @@ function partition(s: string): string[][] {
};
```
## C
### C
```c
char** path;
@ -679,7 +677,7 @@ char*** partition(char* s, int* returnSize, int** returnColumnSizes){
}
```
## Swift
### Swift
```swift
func partition(_ s: String) -> [[String]] {
@ -719,7 +717,7 @@ func partition(_ s: String) -> [[String]] {
}
```
## Rust
### Rust
**回溯+函数判断回文串**
```Rust
@ -808,7 +806,7 @@ impl Solution {
```
## Scala
### Scala
```scala
object Solution {
@ -855,3 +853,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -34,7 +34,7 @@
* 1 <= s.length <= 2000
* s 仅由小写英文字母组成
# 思路
## 思路
我们在讲解回溯法系列的时候,讲过了这道题目[回溯算法131.分割回文串](https://programmercarl.com/0131.分割回文串.html)。
@ -201,9 +201,9 @@ public:
```
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
class Solution {
@ -257,7 +257,7 @@ class Solution {
}
```
## Python
### Python
```python
class Solution:
@ -286,7 +286,7 @@ class Solution:
return dp[-1]
```
## Go
### Go
```go
func minCut(s string) int {
@ -330,7 +330,7 @@ func min(i, j int) int {
}
```
## JavaScript
### JavaScript
```js
var minCut = function(s) {
@ -376,3 +376,4 @@ var minCut = function(s) {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -45,12 +45,14 @@
* 解释:
你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油。开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油。开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油。你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。因此,无论怎样,你都不可能绕环路行驶一周。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法得这么加油才能跑完全程LeetCode 134.加油站](https://www.bilibili.com/video/BV1jA411r7WX),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法得这么加油才能跑完全程LeetCode 134.加油站](https://www.bilibili.com/video/BV1jA411r7WX),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
## 暴力方法
### 暴力方法
暴力的方法很明显就是O(n^2)的,遍历每一个加油站为起点的情况,模拟一圈。
@ -85,7 +87,7 @@ public:
* 空间复杂度O(1)
## 贪心算法(方法一)
### 贪心算法(方法一)
直接从全局进行贪心选择,情况如下:
@ -134,7 +136,7 @@ public:
但不管怎么说,解法毕竟还是巧妙的,不用过于执着于其名字称呼。
## 贪心算法(方法二)
### 贪心算法(方法二)
可以换一个思路,首先如果总油量减去总消耗大于等于零那么一定可以跑完一圈,说明 各个站点的加油站 剩油量rest[i]相加一定是大于等于零的。
@ -633,3 +635,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -28,9 +28,9 @@
* 输出: 4
* 解释: 你可以分别给这三个孩子分发 1、2、1 颗糖果。第三个孩子只得到 1 颗糖果,这已满足上述两个条件。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法两者兼顾很容易顾此失彼LeetCode135.分发糖果](https://www.bilibili.com/video/BV1ev4y1r7wN),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法两者兼顾很容易顾此失彼LeetCode135.分发糖果](https://www.bilibili.com/video/BV1ev4y1r7wN),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -234,7 +234,7 @@ func findMax(num1 int, num2 int) int {
}
```
### Javascript:
### Javascript
```Javascript
var candy = function(ratings) {
let candys = new Array(ratings.length).fill(1)
@ -376,3 +376,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -33,9 +33,9 @@
* 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
* 输出: false
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[你的背包如何装满?| LeetCode139.单词拆分](https://www.bilibili.com/video/BV1pd4y147Rh/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[你的背包如何装满?| LeetCode139.单词拆分](https://www.bilibili.com/video/BV1pd4y147Rh/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -123,7 +123,7 @@ public:
**这个代码就可以AC了当然回溯算法不是本题的主菜背包才是**
## 背包问题
### 背包问题
单词就是物品字符串s就是背包单词能否组成字符串s就是问物品能不能把背包装满。
@ -239,7 +239,7 @@ public:
}
};
```
```
使用用例s = "applepenapple", wordDict = ["apple", "pen"]对应的dp数组状态如下
@ -259,8 +259,8 @@ public:
## 其他语言版本
### Java
Java
```java
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
@ -335,7 +335,7 @@ class Solution {
}
```
Python
### Python
回溯
```python
@ -397,7 +397,8 @@ class Solution:
Go
### Go
```Go
func wordBreak(s string,wordDict []string) bool {
wordDictSet := make(map[string]bool)
@ -433,7 +434,8 @@ func wordBreak(s string, wordDict []string) bool {
}
```
Javascript
### JavaScript
```javascript
const wordBreak = (s, wordDict) => {
@ -454,7 +456,7 @@ const wordBreak = (s, wordDict) => {
}
```
TypeScript
### TypeScript
> 动态规划
@ -496,7 +498,7 @@ function wordBreak(s: string, wordDict: string[]): boolean {
};
```
Rust:
### Rust:
```rust
impl Solution {
@ -519,3 +521,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -433,7 +433,7 @@ class Solution {
}
```
### python:
### Python:
(版本一)先删除空白,然后整个反转,最后单词反转。
**因为字符串是不可变类型所以反转单词的时候需要将其转换成列表然后通过join函数再将其转换成列表所以空间复杂度不是O(1)**
@ -547,26 +547,28 @@ func reverseWords(s string) string {
b = b[:slowIndex]
}
//2.反转整个字符串
reverse(&b, 0, len(b)-1)
reverse(b)
//3.反转单个单词 i单词开始位置j单词结束位置
i := 0
for i < len(b) {
j := i
for ; j < len(b) && b[j] != ' '; j++ {
}
reverse(&b, i, j-1)
reverse(b[i:j])
i = j
i++
}
return string(b)
}
func reverse(b *[]byte, left, right int) {
for left < right {
(*b)[left], (*b)[right] = (*b)[right], (*b)[left]
left++
right--
}
func reverse(b []byte) {
left := 0
right := len(b) - 1
for left < right {
b[left], b[right] = b[right], b[left]
left++
right--
}
}
```
@ -974,4 +976,3 @@ char * reverseWords(char * s){
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -31,9 +31,9 @@
* 0 <= prices.length <= 1000
* 0 <= prices[i] <= 1000
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划来决定最佳时机至多可以买卖K次| LeetCode188.买卖股票最佳时机4](https://www.bilibili.com/video/BV16M411U7XJ),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划来决定最佳时机至多可以买卖K次| LeetCode188.买卖股票最佳时机4](https://www.bilibili.com/video/BV16M411U7XJ),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -173,7 +173,7 @@ public:
## 其他语言版本
Java:
### Java:
```java
// 版本一: 三维 dp数组
@ -295,7 +295,7 @@ class Solution {
}
```
Python:
### Python:
版本一
@ -329,7 +329,7 @@ class Solution:
dp[j] = max(dp[j],dp[j-1]+prices[i])
return dp[2*k]
```
Go:
### Go:
版本一:
@ -404,7 +404,7 @@ func max188(a, b int) int {
}
```
Javascript:
### JavaScript:
```javascript
// 方法一:动态规划
@ -454,7 +454,7 @@ var maxProfit = function(k, prices) {
};
```
TypeScript
### TypeScript
```typescript
function maxProfit(k: number, prices: number[]): number {
@ -474,7 +474,7 @@ function maxProfit(k: number, prices: number[]): number {
};
```
Rust
### Rust
```rust
impl Solution {

View File

@ -33,7 +33,7 @@
向右旋转 2 步: [3,99,-1,-100]。
# 思路
## 思路
这道题目在字符串里其实很常见,我把字符串反转相关的题目列一下:
@ -83,9 +83,9 @@ public:
```
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
class Solution {
@ -106,7 +106,7 @@ class Solution {
}
```
## Python
### Python
方法一:局部翻转 + 整体翻转
```python
@ -139,7 +139,7 @@ class Solution:
# 备注:这个方法会导致空间复杂度变成 O(n) 因为我们要创建一个 copy 数组。但是不失为一种思路。
```
## Go
### Go
```go
func rotate(nums []int, k int) {
@ -157,7 +157,7 @@ func reverse(nums []int){
}
```
## JavaScript
### JavaScript
```js
var rotate = function (nums, k) {
@ -178,7 +178,7 @@ var rotate = function (nums, k) {
};
```
## TypeScript
### TypeScript
```typescript
function rotate(nums: number[], k: number): void {
@ -205,3 +205,4 @@ function reverseByRange(nums: number[], left: number, right: number): void {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -31,9 +31,9 @@
* 0 <= nums.length <= 100
* 0 <= nums[i] <= 400
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,偷不偷这个房间呢?| LeetCode198.打家劫舍](https://www.bilibili.com/video/BV1Te411N7SX),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,偷不偷这个房间呢?| LeetCode198.打家劫舍](https://www.bilibili.com/video/BV1Te411N7SX),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -121,8 +121,8 @@ public:
## 其他语言版本
### Java
Java
```Java
// 动态规划
class Solution {
@ -194,7 +194,7 @@ class Solution {
}
```
Python
### Python
1维DP
```python
@ -255,7 +255,8 @@ class Solution:
```
Go
### Go
```Go
func rob(nums []int) int {
n := len(nums)
@ -275,7 +276,7 @@ func max(a, b int) int {
}
```
JavaScript
### JavaScript
```javascript
const rob = nums => {
@ -291,7 +292,7 @@ const rob = nums => {
};
```
TypeScript
### TypeScript
```typescript
function rob(nums: number[]): number {
@ -314,7 +315,7 @@ function rob(nums: number[]): number {
};
```
Rust:
### Rust:
```rust
impl Solution {
@ -338,4 +339,3 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -197,7 +197,7 @@ class Solution {
}
```
## 其他语言版本
### Python
BFS solution
```python
@ -237,6 +237,7 @@ class Solution:
continue
q.append((next_i, next_j))
visited[next_i][next_j] = True
```
<p align="center">
@ -244,3 +245,4 @@ class Solution:
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>
```

View File

@ -218,6 +218,67 @@ class Solution {
}
}
```
Python:
```python
# 版本一
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
visited = [[False] * n for _ in range(m)]
dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] # 四个方向
result = 0
def dfs(x, y):
for d in dirs:
nextx = x + d[0]
nexty = y + d[1]
if nextx < 0 or nextx >= m or nexty < 0 or nexty >= n: # 越界了,直接跳过
continue
if not visited[nextx][nexty] and grid[nextx][nexty] == '1': # 没有访问过的同时是陆地的
visited[nextx][nexty] = True
dfs(nextx, nexty)
for i in range(m):
for j in range(n):
if not visited[i][j] and grid[i][j] == '1':
visited[i][j] = True
result += 1 # 遇到没访问过的陆地,+1
dfs(i, j) # 将与其链接的陆地都标记上 true
return result
```
```python
# 版本二
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
visited = [[False] * n for _ in range(m)]
dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] # 四个方向
result = 0
def dfs(x, y):
if visited[x][y] or grid[x][y] == '0':
return # 终止条件:访问过的节点 或者 遇到海水
visited[x][y] = True
for d in dirs:
nextx = x + d[0]
nexty = y + d[1]
if nextx < 0 or nextx >= m or nexty < 0 or nexty >= n: # 越界了,直接跳过
continue
dfs(nextx, nexty)
for i in range(m):
for j in range(n):
if not visited[i][j] and grid[i][j] == '1':
result += 1 # 遇到没访问过的陆地,+1
dfs(i, j) # 将与其链接的陆地都标记上 true
return result
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

View File

@ -29,7 +29,7 @@
提示:可以假设 s 和 t 长度相同。
# 思路
## 思路
字符串没有说都是小写字母之类的所以用数组不合适了用map来做映射。
@ -61,9 +61,9 @@ public:
```
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
class Solution {
@ -87,7 +87,7 @@ class Solution {
}
```
## Python
### Python
```python
class Solution:
@ -110,7 +110,7 @@ class Solution:
return True
```
## Go
### Go
```go
func isIsomorphic(s string, t string) bool {
@ -132,7 +132,7 @@ func isIsomorphic(s string, t string) bool {
}
```
## JavaScript
### JavaScript
```js
var isIsomorphic = function(s, t) {
@ -156,7 +156,7 @@ var isIsomorphic = function(s, t) {
};
```
## TypeScript
### TypeScript
```typescript
function isIsomorphic(s: string, t: string): boolean {
@ -183,3 +183,4 @@ function isIsomorphic(s: string, t: string): boolean {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -31,9 +31,9 @@
* 1 <= nums.length <= 100
* 0 <= nums[i] <= 1000
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,房间连成环了那还偷不偷呢?| LeetCode213.打家劫舍II](https://www.bilibili.com/video/BV1oM411B7xq),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,房间连成环了那还偷不偷呢?| LeetCode213.打家劫舍II](https://www.bilibili.com/video/BV1oM411B7xq),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -104,8 +104,8 @@ public:
## 其他语言版本
### Java
Java
```Java
class Solution {
public int rob(int[] nums) {
@ -129,7 +129,7 @@ class Solution {
}
```
Python
### Python
```Python
class Solution:
@ -219,7 +219,7 @@ class Solution:
```
Go
### Go
```go
// 打家劫舍Ⅱ 动态规划
@ -257,7 +257,8 @@ func max(a, b int) int {
}
```
javascipt:
### JavaScript:
```javascript
var rob = function(nums) {
const n = nums.length
@ -279,7 +280,7 @@ const robRange = (nums, start, end) => {
return dp[end]
}
```
TypeScript
### TypeScript
```typescript
function rob(nums: number[]): number {
@ -301,7 +302,7 @@ function robRange(nums: number[], start: number, end: number): number {
}
```
Rust:
### Rust:
```rust
impl Solution {
@ -336,3 +337,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -7,8 +7,6 @@
> 别看本篇选的是组合总和III而不是组合总和本题和上一篇77.组合相比难度刚刚好!
# 216.组合总和III
@ -30,12 +28,12 @@
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[和组合问题有啥区别?回溯算法如何剪枝?| LeetCode216.组合总和III](https://www.bilibili.com/video/BV1wg411873x),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[和组合问题有啥区别?回溯算法如何剪枝?| LeetCode216.组合总和III](https://www.bilibili.com/video/BV1wg411873x),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
本题就是在[1,2,3,4,5,6,7,8,9]这个集合中找到和为n的k个数的组合。
@ -54,7 +52,7 @@
图中可以看出只有最后取到集合13和为4 符合条件。
## 回溯三部曲
### 回溯三部曲
* **确定递归函数参数**
@ -165,7 +163,7 @@ public:
};
```
## 剪枝
### 剪枝
这道题目,剪枝操作其实是很容易想到了,想必大家看上面的树形图的时候已经想到了。
@ -238,7 +236,7 @@ public:
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
# 总结
## 总结
开篇就介绍了本题与[77.组合](https://programmercarl.com/0077.组合.html)的区别,相对来说加了元素总和的限制,如果做完[77.组合](https://programmercarl.com/0077.组合.html)再做本题在合适不过。
@ -249,10 +247,10 @@ public:
# 其他语言版本
## 其他语言版本
## Java
### Java
模板方法
@ -358,7 +356,7 @@ class Solution {
}
```
## Python
### Python
```py
class Solution:
@ -383,7 +381,7 @@ class Solution:
```
## Go
### Go
回溯+减枝
@ -418,7 +416,7 @@ func dfs(k, n int, start int, sum int) {
}
```
## javaScript
### JavaScript
```js
/**
@ -455,7 +453,7 @@ var combinationSum3 = function(k, n) {
};
```
## TypeScript
### TypeScript
```typescript
function combinationSum3(k: number, n: number): number[][] {
@ -479,7 +477,7 @@ function combinationSum3(k: number, n: number): number[][] {
};
```
## Rust
### Rust
```Rust
impl Solution {
@ -516,7 +514,7 @@ impl Solution {
}
```
## C
### C
```c
int* path;
@ -575,7 +573,7 @@ int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes){
}
```
## Swift
### Swift
```swift
func combinationSum3(_ count: Int, _ targetSum: Int) -> [[Int]] {
@ -607,7 +605,7 @@ func combinationSum3(_ count: Int, _ targetSum: Int) -> [[Int]] {
}
```
## Scala
### Scala
```scala
object Solution {

View File

@ -432,3 +432,4 @@ function reverseList(head: ListNode | null): ListNode | null {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -36,11 +36,11 @@
* 所有节点的值都是唯一的。
* p、q 为不同节点且均存在于给定的二叉搜索树中。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[二叉搜索树找祖先就有点不一样了!| 235. 二叉搜索树的最近公共祖先](https://www.bilibili.com/video/BV1Zt4y1F7ww?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[二叉搜索树找祖先就有点不一样了!| 235. 二叉搜索树的最近公共祖先](https://www.bilibili.com/video/BV1Zt4y1F7ww?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
做过[二叉树:公共祖先问题](https://programmercarl.com/0236.二叉树的最近公共祖先.html)题目的同学应该知道利用回溯从底向上搜索遇到一个节点的左子树里有p右子树里有q那么当前节点就是最近公共祖先。
@ -71,7 +71,7 @@
可以看出直接按照指定的方向就可以找到节点8为最近公共祖先而且不需要遍历整棵树找到结果直接返回
## 递归法
### 递归法
递归三部曲如下:
@ -203,7 +203,7 @@ public:
};
```
## 迭代法
### 迭代法
对于二叉搜索树的迭代法,大家应该在[二叉树:二叉搜索树登场!](https://programmercarl.com/0700.二叉搜索树中的搜索.html)就了解了。
@ -229,7 +229,7 @@ public:
灵魂拷问:是不是又被简单的迭代法感动到痛哭流涕?
# 总结
## 总结
对于二叉搜索树的最近祖先问题,其实要比[普通二叉树公共祖先问题](https://programmercarl.com/0236.二叉树的最近公共祖先.html)简单的多。
@ -238,10 +238,10 @@ public:
最后给出了对应的迭代法,二叉搜索树的迭代法甚至比递归更容易理解,也是因为其有序性(自带方向性),按照目标区间找就行了。
# 其他语言版本
## 其他语言版本
## Java
### Java
递归法:
```java
@ -273,7 +273,7 @@ class Solution {
```
## Python
### Python
递归法(版本一)
```python
@ -326,7 +326,7 @@ class Solution:
```
## Go
### Go
递归法:
```go
@ -350,7 +350,7 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
```
## JavaScript
### JavaScript
递归法:
```javascript
@ -391,7 +391,7 @@ var lowestCommonAncestor = function(root, p, q) {
};
```
## TypeScript
### TypeScript
> 递归法:
@ -422,7 +422,7 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree
};
```
## Scala
### Scala
递归:
@ -453,7 +453,7 @@ object Solution {
}
```
## rust
### Rust
递归:
@ -519,3 +519,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -34,12 +34,12 @@
* 所有节点的值都是唯一的。
* p、q 为不同节点且均存在于给定的二叉树中。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[自底向上查找,有点难度! | LeetCode236. 二叉树的最近公共祖先](https://www.bilibili.com/video/BV1jd4y1B7E2),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[自底向上查找,有点难度! | LeetCode236. 二叉树的最近公共祖先](https://www.bilibili.com/video/BV1jd4y1B7E2),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
遇到这个题目首先想的是要是能自底向上查找就好了,这样就可以找到公共祖先了。
@ -226,7 +226,7 @@ public:
};
```
# 总结
## 总结
这道题目刷过的同学未必真正了解这里面回溯的过程,以及结果是如何一层一层传上去的。
@ -243,10 +243,10 @@ public:
本题没有给出迭代法,因为迭代法不适合模拟回溯的过程。理解递归的解法就够了。
# 其他语言版本
## 其他语言版本
## Java
### Java
```Java
class Solution {
@ -273,7 +273,7 @@ class Solution {
```
## Python
### Python
递归法(版本一)
```python
class Solution:
@ -312,7 +312,7 @@ class Solution:
return left
```
## Go
### Go
```Go
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
@ -343,7 +343,7 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
}
```
## JavaScript
### JavaScript
```javascript
var lowestCommonAncestor = function(root, p, q) {
@ -370,7 +370,7 @@ var lowestCommonAncestor = function(root, p, q) {
};
```
## TypeScript
### TypeScript
```typescript
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
@ -384,7 +384,7 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree
};
```
## Scala
### Scala
```scala
object Solution {
@ -404,7 +404,7 @@ object Solution {
}
```
## rust
### Rust
```rust
impl Solution {
@ -436,3 +436,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -28,9 +28,9 @@
提示:
* 1 <= n <= 10^4
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[换汤不换药!| LeetCode279.完全平方数](https://www.bilibili.com/video/BV12P411T7Br/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[换汤不换药!| LeetCode279.完全平方数](https://www.bilibili.com/video/BV12P411T7Br/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -106,8 +106,6 @@ dp[5] = min(dp[4] + 1, dp[1] + 1) = 2
最后的dp[n]为最终结果。
## C++代码
以上动规五部曲分析完毕C++代码如下:
```CPP
@ -165,8 +163,8 @@ public:
## 其他语言版本
### Java
Java
```Java
class Solution {
// 版本一,先遍历物品, 再遍历背包
@ -219,7 +217,7 @@ class Solution {
}
```
Python
### Python
先遍历物品, 再遍历背包
```python
@ -276,7 +274,8 @@ class Solution:
```
Go
### Go
```go
// 版本一,先遍历物品, 再遍历背包
func numSquares1(n int) int {
@ -327,7 +326,8 @@ func min(a, b int) int {
}
```
Javascript:
### Javascript:
```Javascript
// 先遍历物品,再遍历背包
var numSquares1 = function(n) {
@ -357,7 +357,7 @@ var numSquares2 = function(n) {
};
```
TypeScript
### TypeScript
```typescript
// 先遍历物品
@ -389,7 +389,7 @@ function numSquares(n: number): number {
};
```
Rust:
### Rust:
```rust
// 先遍历背包
@ -439,3 +439,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -4,9 +4,7 @@
</a>
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
# 动态规划:一样的套路,再求一次完全平方数
# 283. 移动零
# 283. 移动零:动态规划:一样的套路,再求一次完全平方数
[力扣题目链接](https://leetcode.cn/problems/move-zeroes/)
@ -22,7 +20,7 @@
尽量减少操作次数。
# 思路
## 思路
做这道题目之前,大家可以做一做[27.移除元素](https://programmercarl.com/0027.移除元素.html)
@ -58,9 +56,9 @@ public:
};
```
# 其他语言版本
## 其他语言版本
Java
### Java
```java
public void moveZeroes(int[] nums) {
@ -77,7 +75,7 @@ public void moveZeroes(int[] nums) {
}
```
Python
### Python
```python
def moveZeroes(self, nums: List[int]) -> None:
@ -100,7 +98,7 @@ Python
fast += 1
```
Go
### Go
```go
func moveZeroes(nums []int) {
@ -116,7 +114,8 @@ func moveZeroes(nums []int) {
}
```
JavaScript
### JavaScript
```javascript
var moveZeroes = function(nums) {
let slow = 0;
@ -133,7 +132,7 @@ var moveZeroes = function(nums) {
};
```
TypeScript
### TypeScript
```typescript
function moveZeroes(nums: number[]): void {
@ -159,3 +158,4 @@ function moveZeroes(nums: number[]): void {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -33,7 +33,7 @@
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划之子序列问题,元素不连续!| LeetCode300.最长递增子序列](https://www.bilibili.com/video/BV1ng411J7xP),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划之子序列问题,元素不连续!| LeetCode300.最长递增子序列](https://www.bilibili.com/video/BV1ng411J7xP),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -124,30 +124,28 @@ public:
## 其他语言版本
### Java
Java
```Java
class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
int res = 0;
Arrays.fill(dp, 1);
for (int i = 0; i < dp.length; i++) {
for (int i = 1; i < dp.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
res = Math.max(res, dp[i]);
}
}
int res = 0;
for (int i = 0; i < dp.length; i++) {
res = Math.max(res, dp[i]);
}
return res;
}
}
```
Python
### Python
DP
```python
@ -189,7 +187,8 @@ class Solution:
return len(tails) # 返回递增子序列的长度
```
Go
### Go
```go
// 动态规划求解
func lengthOfLIS(nums []int) int {
@ -248,7 +247,8 @@ func lengthOfLIS(nums []int ) int {
}
```
Javascript
### Javascript:
```javascript
const lengthOfLIS = (nums) => {
let dp = Array(nums.length).fill(1);
@ -267,7 +267,7 @@ const lengthOfLIS = (nums) => {
};
```
TypeScript
### TypeScript:
```typescript
function lengthOfLIS(nums: number[]): number {
@ -288,10 +288,11 @@ function lengthOfLIS(nums: number[]): number {
};
```
Rust:
### Rust:
```rust
pub fn length_of_lis(nums: Vec<i32>) -> i32 {
let mut dp = vec![1; nums.len() + 1];
let mut dp = vec![1; nums.len()];
let mut result = 1;
for i in 1..nums.len() {
for j in 0..i {
@ -306,14 +307,8 @@ pub fn length_of_lis(nums: Vec<i32>) -> i32 {
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -20,9 +20,9 @@
* 输出: 3
* 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划来决定最佳时机,这次有冷冻期!| LeetCode309.买卖股票的最佳时机含冷冻期](https://www.bilibili.com/video/BV1rP4y1D7ku),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划来决定最佳时机,这次有冷冻期!| LeetCode309.买卖股票的最佳时机含冷冻期](https://www.bilibili.com/video/BV1rP4y1D7ku),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -174,7 +174,7 @@ public:
## 其他语言版本
Java
### Java
```java
class Solution {
@ -273,8 +273,9 @@ class Solution {
}
```
Python
### Python
版本一
```python
from typing import List
@ -319,7 +320,8 @@ class Solution:
return max(dp[-1][1], dp[-1][2])
```
Go
### Go
```go
// 最佳买卖股票时机含冷冻期 动态规划
// 时间复杂度O(n) 空间复杂度O(n)
@ -355,7 +357,7 @@ func max(a, b int) int {
}
```
Javascript:
### Javascript:
```javascript
const maxProfit = (prices) => {
@ -397,7 +399,7 @@ const maxProfit = (prices) => {
};
```
TypeScript
### TypeScript
> 版本一,与本文思路一致
@ -455,7 +457,7 @@ function maxProfit(prices: number[]): number {
};
```
Rust
### Rust
```rust
impl Solution {
@ -484,3 +486,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -39,9 +39,9 @@
* 1 <= coins[i] <= 2^31 - 1
* 0 <= amount <= 10^4
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[装满背包最少的物品件数是多少?| LeetCode322.零钱兑换](https://www.bilibili.com/video/BV14K411R7yv/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[装满背包最少的物品件数是多少?| LeetCode322.零钱兑换](https://www.bilibili.com/video/BV14K411R7yv/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
@ -110,7 +110,6 @@ dp[0] = 0;
dp[amount]为最终结果。
## C++代码
以上分析完毕C++ 代码如下:
```CPP
@ -187,8 +186,8 @@ public:
## 其他语言版本
### Java
Java
```Java
class Solution {
public int coinChange(int[] coins, int amount) {
@ -215,7 +214,7 @@ class Solution {
}
```
Python
### Python
先遍历物品 后遍历背包
@ -288,7 +287,8 @@ class Solution:
```
Go
### Go
```go
// 版本一, 先遍历物品,再遍历背包
func coinChange1(coins []int, amount int) int {
@ -352,7 +352,7 @@ func min(a, b int) int {
```
Rust:
### Rust:
```rust
// 遍历物品
@ -398,7 +398,8 @@ impl Solution {
}
```
Javascript
### Javascript
```javascript
// 遍历物品
const coinChange = (coins, amount) => {
@ -435,7 +436,7 @@ var coinChange = function(coins, amount) {
}
```
TypeScript
### TypeScript
```typescript
// 遍历物品
@ -473,3 +474,4 @@ function coinChange(coins: number[], amount: number): number {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -29,9 +29,11 @@
* 输出:["JFK","ATL","JFK","SFO","ATL","SFO"]
* 解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"]。但是它自然排序更大更靠后。
## 思路
## 算法公开课
**如果对回溯算法基础还不了解的话,我还特意录制了一期视频:[带你学透回溯算法(理论篇)](https://www.bilibili.com/video/BV1cy4y167mM/)** 可以结合题解和视频一起看,希望对大家理解回溯算法有所帮助。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[带你学透回溯算法(理论篇)](https://www.bilibili.com/video/BV1cy4y167mM/) ,相信结合视频再看本篇题解,更有助于大家对本题的理解。**
## 思路
这道题目还是很难的,之前我们用回溯法解决了如下问题:[组合问题](https://programmercarl.com/0077.组合.html)[分割问题](https://programmercarl.com/0093.复原IP地址.html)[子集问题](https://programmercarl.com/0078.子集.html)[排列问题](https://programmercarl.com/0046.全排列.html)。
@ -53,7 +55,7 @@
针对以上问题我来逐一解答!
## 如何理解死循环
### 如何理解死循环
对于死循环,我来举一个有重复机场的例子:
@ -61,7 +63,7 @@
为什么要举这个例子呢,就是告诉大家,出发机场和到达机场也会重复的,**如果在解题的过程中没有对集合元素处理好,就会死循环。**
## 该记录映射关系
### 该记录映射关系
有多种解法,字母序靠前排在前面,让很多同学望而退步,如何该记录映射关系呢
@ -90,7 +92,7 @@ unordered_map<string, map<string, int>> targetsunordered_map<出发机场, ma
**相当于说我不删,我就做一个标记!**
## 回溯法
### 回溯法
这道题目我使用回溯法,那么下面按照我总结的回溯模板来:
@ -260,8 +262,8 @@ for (pair<string, int>target : targets[result[result.size() - 1]])
## 其他语言版本
### java
### Java
```java
class Solution {
private LinkedList<String> res;
@ -346,7 +348,7 @@ class Solution {
}
```
### python
### Python
回溯 使用used数组
```python
@ -406,7 +408,7 @@ class Solution:
path.pop() # 移除目的地
return False # 没有找到有效行程
```
```
回溯 使用字典 逆序
```python
from collections import defaultdict
@ -430,8 +432,8 @@ class Solution:
self.backtracking(next_airport, targets, result) # 递归调用回溯函数进行深度优先搜索
result.append(airport) # 将当前机场添加到行程路径中
```
### GO
### Go
```go
type pair struct {
target string
@ -577,7 +579,7 @@ function findItinerary(tickets: string[][]): string[] {
};
```
### C语言
### C
```C
char **result;
@ -638,7 +640,7 @@ char ** findItinerary(char *** tickets, int ticketsSize, int* ticketsColSize, in
return result;
}
```
### Swift
直接迭代tickets数组

View File

@ -16,9 +16,9 @@
![337.打家劫舍III](https://code-thinking-1253855093.file.myqcloud.com/pics/20210223173849619.png)
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,房间连成树了,偷不偷呢?| LeetCode337.打家劫舍3](https://www.bilibili.com/video/BV1H24y1Q7sY),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,房间连成树了,偷不偷呢?| LeetCode337.打家劫舍3](https://www.bilibili.com/video/BV1H24y1Q7sY),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -523,3 +523,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -22,9 +22,9 @@
* 说明: 你可以假设 n 不小于 2 且不大于 58。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,本题关键在于理解递推公式!| LeetCode343. 整数拆分](https://www.bilibili.com/video/BV1Mg411q7YJ/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,本题关键在于理解递推公式!| LeetCode343. 整数拆分](https://www.bilibili.com/video/BV1Mg411q7YJ/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -473,3 +473,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -33,11 +33,13 @@
- 输入: [1,2,3,4,5,6,7,8,9]
- 输出: 2
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法,寻找摆动有细节!| LeetCode376.摆动序列](https://www.bilibili.com/video/BV17M411b7NS),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法,寻找摆动有细节!| LeetCode376.摆动序列](https://www.bilibili.com/video/BV17M411b7NS),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路 1贪心解法
## 思路
### 思路 1贪心解法
本题要求通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。
@ -69,7 +71,7 @@
2. 情况二:数组首尾两端
3. 情况三:单调坡中有平坡
### 情况一:上下坡中有平坡
#### 情况一:上下坡中有平坡
例如 [1,2,2,2,1]这样的数组,如图:
@ -87,7 +89,7 @@
所以我们记录峰值的条件应该是: `(preDiff <= 0 && curDiff > 0) || (preDiff >= 0 && curDiff < 0)`,为什么这里允许 prediff == 0 ,就是为了 上面我说的这种情况。
### 情况二:数组首尾两端
#### 情况二:数组首尾两端
所以本题统计峰值的时候,数组最左面和最右面如何统计呢?
@ -142,7 +144,7 @@ public:
所以此时我们要讨论情况三!
### 情况三:单调坡度有平坡
#### 情况三:单调坡度有平坡
在版本一中,我们忽略了一种情况,即 如果在一个单调坡度上有平坡,例如[1,2,2,2,3,4],如图:
@ -187,7 +189,7 @@ public:
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230108174452.png)
## 思路 2动态规划
### 思路 2动态规划
考虑用动态规划的思想来解决这个问题。
@ -696,4 +698,3 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -31,9 +31,9 @@
因此输出为 7。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[装满背包有几种方法?求排列数?| LeetCode377.组合总和IV](https://www.bilibili.com/video/BV1V14y1n7B6/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[装满背包有几种方法?求排列数?| LeetCode377.组合总和IV](https://www.bilibili.com/video/BV1V14y1n7B6/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -154,8 +154,7 @@ C++测试用例有两个数相加超过int的数据所以需要在if里加上
## 其他语言版本
Java
### Java
```Java
class Solution {
@ -174,7 +173,7 @@ class Solution {
}
```
Python
### Python
卡哥版
@ -207,7 +206,8 @@ class Solution:
```
Go
### Go
```go
func combinationSum4(nums []int, target int) int {
//定义dp数组
@ -226,7 +226,8 @@ func combinationSum4(nums []int, target int) int {
}
```
Javascript
### Javascript
```javascript
const combinationSum4 = (nums, target) => {
@ -245,7 +246,7 @@ const combinationSum4 = (nums, target) => {
};
```
TypeScript
### TypeScript
```typescript
function combinationSum4(nums: number[], target: number): number {
@ -264,7 +265,7 @@ function combinationSum4(nums: number[], target: number): number {
};
```
Rust
### Rust:
```Rust
impl Solution {
@ -289,3 +290,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -28,9 +28,9 @@
两个字符串都只由小写字符组成。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划,用相似思路解决复杂问题 | LeetCode392.判断子序列](https://www.bilibili.com/video/BV1tv4y1B7ym/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划,用相似思路解决复杂问题 | LeetCode392.判断子序列](https://www.bilibili.com/video/BV1tv4y1B7ym/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -149,8 +149,8 @@ public:
## 其他语言版本
### Java:
Java:
```java
class Solution {
public boolean isSubsequence(String s, String t) {
@ -174,7 +174,8 @@ class Solution {
}
```
Python
### Python
```python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
@ -190,7 +191,7 @@ class Solution:
return False
```
JavaScript
### JavaScript
```javascript
const isSubsequence = (s, t) => {
@ -213,7 +214,7 @@ const isSubsequence = (s, t) => {
};
```
TypeScript
### TypeScript
```typescript
function isSubsequence(s: string, t: string): boolean {
@ -237,7 +238,7 @@ function isSubsequence(s: string, t: string): boolean {
};
```
Go
### Go
```go
func isSubsequence(s string, t string) bool {
@ -258,11 +259,52 @@ func isSubsequence(s string, t string) bool {
}
```
Rust
```rust
impl Solution {
pub fn is_subsequence(s: String, t: String) -> bool {
let mut dp = vec![vec![0; t.len() + 1]; s.len() + 1];
for (i, char_s) in s.chars().enumerate() {
for (j, char_t) in t.chars().enumerate() {
if char_s == char_t {
dp[i + 1][j + 1] = dp[i][j] + 1;
continue;
}
dp[i + 1][j + 1] = dp[i + 1][j]
}
}
dp[s.len()][t.len()] == s.len()
}
}
```
> 滚动数组
```rust
impl Solution {
pub fn is_subsequence(s: String, t: String) -> bool {
let mut dp = vec![0; t.len() + 1];
let (s, t) = (s.as_bytes(), t.as_bytes());
for &byte_s in s {
let mut pre = 0;
for j in 0..t.len() {
let temp = dp[j + 1];
if byte_s == t[j] {
dp[j + 1] = pre + 1;
} else {
dp[j + 1] = dp[j];
}
pre = temp;
}
}
dp[t.len()] == s.len()
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -16,9 +16,9 @@
![404.左叶子之和1](https://code-thinking-1253855093.file.myqcloud.com/pics/20210204151927654.png)
## 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[二叉树的题目中,总有一些规则让你找不到北 | LeetCode404.左叶子之和](https://www.bilibili.com/video/BV1GY4y1K7z8),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[二叉树的题目中,总有一些规则让你找不到北 | LeetCode404.左叶子之和](https://www.bilibili.com/video/BV1GY4y1K7z8),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -48,7 +48,7 @@ if (node->left != NULL && node->left->left == NULL && node->left->right == NULL)
}
```
## 递归法
### 递归法
递归的遍历顺序为后序遍历(左右中),是因为要通过递归函数的返回值来累加求取左叶子数值之和。
@ -131,11 +131,11 @@ public:
return leftValue + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
```
```
精简之后的代码其实看不出来用的是什么遍历方式了,对于算法初学者以上根据第一个版本来学习。
## 迭代法
### 迭代法
本题迭代法使用前中后序都是可以的,只要把左叶子节点统计出来,就可以了,那么参考文章 [二叉树:听说递归能做的,栈也能做!](https://programmercarl.com/二叉树的迭代遍历.html)和[二叉树:迭代法统一写法](https://programmercarl.com/二叉树的统一迭代法.html)中的写法,可以写出一个前序遍历的迭代法。
@ -177,7 +177,7 @@ public:
## 其他语言版本
### Java
### Java
**递归**
@ -246,7 +246,7 @@ class Solution {
```
### Python
### Python:
递归
```python
# Definition for a binary tree node.
@ -316,7 +316,7 @@ class Solution:
```
### Go
### Go:
**递归法**
@ -368,7 +368,7 @@ func sumOfLeftLeaves(root *TreeNode) int {
```
### JavaScript
### JavaScript:
**递归法**
@ -417,7 +417,7 @@ var sumOfLeftLeaves = function(root) {
};
```
### TypeScript
### TypeScript:
> 递归法
@ -462,7 +462,7 @@ function sumOfLeftLeaves(root: TreeNode | null): number {
};
```
### Swift
### Swift:
**递归法**
```swift
@ -511,7 +511,7 @@ func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
}
```
### C
### C:
递归法:
```c
int sumOfLeftLeaves(struct TreeNode* root){
@ -561,7 +561,7 @@ int sumOfLeftLeaves(struct TreeNode* root){
}
```
### Scala
### Scala:
**递归:**
```scala
@ -600,7 +600,7 @@ object Solution {
}
```
### Rust
### Rust:
**递归**
@ -656,3 +656,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -37,9 +37,9 @@
题目数据确保队列可以被重建
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法,不要两边一起贪,会顾此失彼 | LeetCode406.根据身高重建队列](https://www.bilibili.com/video/BV1EA411675Y),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法,不要两边一起贪,会顾此失彼 | LeetCode406.根据身高重建队列](https://www.bilibili.com/video/BV1EA411675Y),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -402,3 +402,4 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -4,7 +4,7 @@
</a>
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
## 416. 分割等和子集
# 416. 分割等和子集
[力扣题目链接](https://leetcode.cn/problems/partition-equal-subset-sum/)
@ -30,9 +30,9 @@
* 1 <= nums.length <= 200
* 1 <= nums[i] <= 100
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划之背包问题,这个包能装满吗?| LeetCode416.分割等和子集](https://www.bilibili.com/video/BV1rt4y1N7jE/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[动态规划之背包问题,这个包能装满吗?| LeetCode416.分割等和子集](https://www.bilibili.com/video/BV1rt4y1N7jE/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -53,7 +53,7 @@
* [动态规划关于01背包问题你该了解这些](https://programmercarl.com/背包理论基础01背包-1.html)
* [动态规划关于01背包问题你该了解这些滚动数组](https://programmercarl.com/背包理论基础01背包-2.html)
## 01背包问题
### 01背包问题
背包问题大家都知道有N件物品和一个最多能背重量为W 的背包。第i件物品的重量是weight[i]得到的价值是value[i] 。每件物品只能用一次,求解将哪些物品装入背包里物品价值总和最大。
@ -479,7 +479,7 @@ func canPartition(nums []int) bool {
}
```
### javaScript:
### JavaScript:
```js
var canPartition = function(nums) {
@ -499,7 +499,7 @@ var canPartition = function(nums) {
```
### Rust
### Rust:
```Rust
impl Solution {
@ -681,7 +681,7 @@ function canPartition(nums: number[]): boolean {
};
```
### Scala
### Scala:
滚动数组:
```scala

View File

@ -30,9 +30,9 @@
* 输出: 0
* 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法,依然是判断重叠区间 | LeetCode435.无重叠区间](https://www.bilibili.com/video/BV1A14y1c7E1),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法,依然是判断重叠区间 | LeetCode435.无重叠区间](https://www.bilibili.com/video/BV1A14y1c7E1),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -89,9 +89,9 @@ public:
大家此时会发现如此复杂的一个问题,代码实现却这么简单!
## 补充
## 补充1
### 补充1
左边界排序可不可以呢?
@ -144,7 +144,7 @@ public:
```
## 补充2
### 补充2
本题其实和[452.用最少数量的箭引爆气球](https://programmercarl.com/0452.用最少数量的箭引爆气球.html)非常像,弓箭的数量就相当于是非交叉区间的数量,只要把弓箭那道题目代码里射爆气球的判断条件加个等号(认为[01][12]不是相邻区间),然后用总区间数减去弓箭数量 就是要移除的区间数量了。
@ -311,7 +311,7 @@ func min(a, b int) int {
}
```
### Javascript:
### Javascript
- 按右边界排序
```Javascript
var eraseOverlapIntervals = function(intervals) {
@ -447,3 +447,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -24,15 +24,15 @@
![450.删除二叉搜索树中的节点](https://code-thinking-1253855093.file.myqcloud.com/pics/20201020171048265.png)
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[调整二叉树的结构最难!| LeetCode450.删除二叉搜索树中的节点](https://www.bilibili.com/video/BV1tP41177us?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[调整二叉树的结构最难!| LeetCode450.删除二叉搜索树中的节点](https://www.bilibili.com/video/BV1tP41177us?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
搜索树的节点删除要比节点增加复杂的多,有很多情况需要考虑,做好心理准备。
## 递归
### 递归
递归三部曲:
@ -161,7 +161,7 @@ public:
};
```
## 普通二叉树的删除方式
### 普通二叉树的删除方式
这里我在介绍一种通用的删除,普通二叉树的删除方式(没有使用搜索树的特性,遍历整棵树),用交换值的操作来删除目标节点。
@ -198,7 +198,7 @@ public:
这个代码是简短一些,思路也巧妙,但是不太好想,实操性不强,推荐第一种写法!
## 迭代法
### 迭代法
删除节点的迭代法还是复杂一些的,但其本质我在递归法里都介绍了,最关键就是删除节点的操作(动画模拟的过程)
@ -246,7 +246,7 @@ public:
};
```
# 总结
## 总结
读完本篇,大家会发现二叉搜索树删除节点比增加节点复杂的多。
@ -264,10 +264,38 @@ public:
迭代法其实不太容易写出来,所以如果是初学者的话,彻底掌握第一种递归写法就够了。
# 其他语言版本
## 其他语言版本
### Java
```java
// 解法1(最好理解的版本)
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return root;
if (root.val == key) {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
} else {
TreeNode cur = root.right;
while (cur.left != null) {
cur = cur.left;
}
cur.left = root.left;
root = root.right;
return root;
}
}
if (root.val > key) root.left = deleteNode(root.left, key);
if (root.val < key) root.right = deleteNode(root.right, key);
return root;
}
}
```
## Java
```java
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
@ -296,34 +324,59 @@ class Solution {
}
}
```
递归法
```java
// 解法2
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return root;
if (root.val == key) {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
} else {
TreeNode cur = root.right;
while (cur.left != null) {
cur = cur.left;
}
cur.left = root.left;
root = root.right;
return root;
if (root == null){
return null;
}
//寻找对应的对应的前面的节点,以及他的前一个节点
TreeNode cur = root;
TreeNode pre = null;
while (cur != null){
if (cur.val < key){
pre = cur;
cur = cur.right;
} else if (cur.val > key) {
pre = cur;
cur = cur.left;
}else {
break;
}
}
if (root.val > key) root.left = deleteNode(root.left, key);
if (root.val < key) root.right = deleteNode(root.right, key);
if (pre == null){
return deleteOneNode(cur);
}
if (pre.left !=null && pre.left.val == key){
pre.left = deleteOneNode(cur);
}
if (pre.right !=null && pre.right.val == key){
pre.right = deleteOneNode(cur);
}
return root;
}
public TreeNode deleteOneNode(TreeNode node){
if (node == null){
return null;
}
if (node.right == null){
return node.left;
}
TreeNode cur = node.right;
while (cur.left !=null){
cur = cur.left;
}
cur.left = node.left;
return node.right;
}
}
```
## Python
### Python
递归法(版本一)
```python
class Solution:
@ -411,7 +464,7 @@ class Solution:
return root
```
## Go
### Go
```Go
// 递归版本
func deleteNode(root *TreeNode, key int) *TreeNode {
@ -497,7 +550,7 @@ func deleteNode(root *TreeNode, key int) *TreeNode {
}
```
## JavaScript
### JavaScript
递归
@ -588,7 +641,7 @@ var deleteNode = function (root, key) {
}
```
## TypeScript
### TypeScript
> 递归法:
@ -652,7 +705,7 @@ function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
};
```
## Scala
### Scala
```scala
object Solution {
@ -682,7 +735,7 @@ object Solution {
}
```
## rust
### Rust
```rust
impl Solution {
@ -720,3 +773,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -42,9 +42,9 @@
* points[i].length == 2
* -2^31 <= xstart < xend <= 2^31 - 1
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法,判断重叠区间问题 | LeetCode452.用最少数量的箭引爆气球](https://www.bilibili.com/video/BV1SA41167xe),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法,判断重叠区间问题 | LeetCode452.用最少数量的箭引爆气球](https://www.bilibili.com/video/BV1SA41167xe),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路

View File

@ -30,9 +30,9 @@
- 0 <= s.length <= 3 \* 10^4
- 1 <= g[i], s[j] <= 2^31 - 1
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[贪心算法,你想先喂哪个小孩?| LeetCode455.分发饼干](https://www.bilibili.com/video/BV1MM411b7cq),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[贪心算法,你想先喂哪个小孩?| LeetCode455.分发饼干](https://www.bilibili.com/video/BV1MM411b7cq),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路

View File

@ -90,7 +90,7 @@ public:
## 其他语言版本
Java
### Java
```java
// 解法一
@ -191,8 +191,8 @@ class Solution {
```
Python
### 解法1:
### Python
扫描每个cell,如果当前位置为岛屿 grid[i][j] == 1 从当前位置判断四边方向如果边界或者是水域证明有边界存在res矩阵的对应cell加一。
```python
@ -228,7 +228,8 @@ class Solution:
```
Go
### Go
```go
func islandPerimeter(grid [][]int) int {
m, n := len(grid), len(grid[0])
@ -249,7 +250,8 @@ func islandPerimeter(grid [][]int) int {
}
```
JavaScript
### JavaScript
```javascript
//解法一
var islandPerimeter = function(grid) {
@ -305,3 +307,4 @@ var islandPerimeter = function(grid) {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -34,9 +34,9 @@
* strs[i] 仅由 '0' 和 '1' 组成
* 1 <= m, n <= 100
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[装满这个背包最多用多少个物品?| LeetCode474.一和零](https://www.bilibili.com/video/BV1rW4y1x7ZQ/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[装满这个背包最多用多少个物品?| LeetCode474.一和零](https://www.bilibili.com/video/BV1rW4y1x7ZQ/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -538,3 +538,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -23,9 +23,9 @@
* 数组中的整数范围是 [-100,100]。
* 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[回溯算法精讲,树层去重与树枝去重 | LeetCode491.递增子序列](https://www.bilibili.com/video/BV1EG4y1h78v/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[回溯算法精讲,树层去重与树枝去重 | LeetCode491.递增子序列](https://www.bilibili.com/video/BV1EG4y1h78v/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -619,4 +619,3 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -37,9 +37,9 @@
* 初始的数组的和不会超过 1000 。
* 保证返回的最终结果能被 32 位整数存下。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[装满背包有多少种方法?| LeetCode494.目标和](https://www.bilibili.com/video/BV1o8411j73x/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[装满背包有多少种方法?| LeetCode494.目标和](https://www.bilibili.com/video/BV1o8411j73x/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -67,7 +67,7 @@ target是固定的sum是固定的left就可以求出来。
此时问题就是在集合nums中找出和为left的组合。
## 回溯算法
### 回溯算法
在回溯算法系列中,一起学过这道题目[回溯算法39. 组合总和](https://programmercarl.com/0039.组合总和.html)的录友应该感觉很熟悉,这不就是组合总和问题么?
@ -118,7 +118,7 @@ public:
也可以使用记忆化回溯,但这里我就不在回溯上下功夫了,直接看动规吧
## 动态规划
### 动态规划
如何转化为01背包问题呢。
@ -519,8 +519,6 @@ const findTargetSumWays = (nums, target) => {
### TypeScript
TypeScript:
```ts
function findTargetSumWays(nums: number[], target: number): number {
// 把数组分成两个组合left, right.left + right = sum, left - right = target.
@ -590,3 +588,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -37,7 +37,7 @@ nums1 中数字 x 的下一个更大元素是指 x  nums2 中对应位
* nums1和nums2中所有整数 互不相同
* nums1 中的所有整数同样出现在 nums2 中
# 思路
## 思路
做本题之前,建议先做一下[739. 每日温度](https://programmercarl.com/0739.每日温度.html)
@ -191,7 +191,8 @@ public:
建议大家把情况一二三想清楚了,先写出版本一的代码,然后在其基础上在做精简!
## 其他语言版本
Java
### Java
```java
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
@ -248,7 +249,8 @@ class Solution {
}
}
```
Python3
### Python3
```python
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
@ -269,7 +271,7 @@ class Solution:
return result
```
Go
### Go
> 未精简版本
```go
@ -335,7 +337,7 @@ func nextGreaterElement(nums1 []int, nums2 []int) []int {
}
```
JavaScript:
### JavaScript
```JS
var nextGreaterElement = function (nums1, nums2) {
@ -358,7 +360,7 @@ var nextGreaterElement = function (nums1, nums2) {
};
```
TypeScript
### TypeScript
```typescript
function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
@ -387,9 +389,36 @@ function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
};
```
### Rust
```rust
impl Solution {
pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut ans = vec![-1; nums1.len()];
use std::collections::HashMap;
let mut map = HashMap::new();
for (idx, &i) in nums1.iter().enumerate() {
map.insert(i, idx);
}
let mut stack = vec![];
for (idx, &i) in nums2.iter().enumerate() {
while !stack.is_empty() && nums2[*stack.last().unwrap()] < i {
let pos = stack.pop().unwrap();
if let Some(&jdx) = map.get(&nums2[pos]) {
ans[jdx] = i;
}
}
stack.push(idx);
}
ans
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -33,20 +33,20 @@
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[不仅双指针,还有代码技巧可以惊艳到你! | LeetCode501.二叉搜索树中的众数](https://www.bilibili.com/video/BV1fD4y117gp),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[不仅双指针,还有代码技巧可以惊艳到你! | LeetCode501.二叉搜索树中的众数](https://www.bilibili.com/video/BV1fD4y117gp),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
这道题目呢,递归法我从两个维度来讲。
首先如果不是二叉搜索树的话,应该怎么解题,是二叉搜索树,又应该如何解题,两种方式做一个比较,可以加深大家对二叉树的理解。
## 递归法
### 递归法
### 如果不是二叉搜索树
#### 如果不是二叉搜索树
如果不是二叉搜索树最直观的方法一定是把这个树都遍历了用map统计频率把频率排个序最后取前面高频的元素的集合。
@ -140,7 +140,7 @@ public:
**所以如果本题没有说是二叉搜索树的话,那么就按照上面的思路写!**
### 是二叉搜索树
#### 是二叉搜索树
**既然是搜索树,它中序遍历就是有序的**。
@ -271,7 +271,7 @@ public:
```
## 迭代法
### 迭代法
只要把中序遍历转成迭代,中间节点的处理逻辑完全一样。
@ -326,7 +326,7 @@ public:
};
```
# 总结
## 总结
本题在递归法中,我给出了如果是普通二叉树,应该怎么求众数。
@ -345,10 +345,10 @@ public:
> **需要强调的是 leetcode上的耗时统计是非常不准确的看个大概就行一样的代码耗时可以差百分之50以上**所以leetcode的耗时统计别太当回事知道理论上的效率优劣就行了。
# 其他语言版本
## 其他语言版本
## Java
### Java
暴力法
@ -472,7 +472,7 @@ class Solution {
}
}
```
一迭代法
一迭代法
```Java
class Solution {
public int[] findMode(TreeNode root) {
@ -526,7 +526,7 @@ class Solution {
```
## Python
### Python
递归法(版本一)利用字典
@ -640,7 +640,7 @@ class Solution:
return result
```
## Go
### Go
计数法,不使用额外空间,利用二叉树性质,中序遍历
```go
@ -676,7 +676,7 @@ func findMode(root *TreeNode) []int {
}
```
## JavaScript
### JavaScript
使用额外空间map的方法
```javascript
@ -753,7 +753,7 @@ var findMode = function(root) {
};
```
## TypeScript
### TypeScript
> 辅助Map法
@ -852,7 +852,7 @@ function findMode(root: TreeNode | null): number[] {
};
```
## Scala
### Scala
暴力:
```scala
@ -923,7 +923,7 @@ object Solution {
}
```
## rust
### Rust
递归:
@ -1015,3 +1015,4 @@ pub fn find_mode(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -22,7 +22,7 @@
* -10^9 <= nums[i] <= 10^9
# 思路
## 思路
做本题之前建议先做[739. 每日温度](https://programmercarl.com/0739.每日温度.html) 和 [496.下一个更大元素 I](https://programmercarl.com/0496.下一个更大元素I.html)。
@ -138,7 +138,8 @@ public:
## 其他语言版本
Java:
### Java:
```Java
class Solution {
public int[] nextGreaterElements(int[] nums) {
@ -162,7 +163,8 @@ class Solution {
}
```
Python:
### Python:
```python
# 方法 1:
class Solution:
@ -196,7 +198,8 @@ class Solution:
stack.append(i)
return ans
```
Go:
### Go:
```go
func nextGreaterElements(nums []int) []int {
length := len(nums)
@ -218,7 +221,7 @@ func nextGreaterElements(nums []int) []int {
}
```
JavaScript:
### JavaScript:
```JS
/**
@ -242,7 +245,7 @@ var nextGreaterElements = function (nums) {
return res;
};
```
TypeScript
### TypeScript
```typescript
function nextGreaterElements(nums: number[]): number[] {
@ -266,6 +269,25 @@ function nextGreaterElements(nums: number[]): number[] {
};
```
### Rust:
```rust
impl Solution {
pub fn next_greater_elements(nums: Vec<i32>) -> Vec<i32> {
let mut ans = vec![-1; nums.len() * 2];
let mut stack = vec![];
let double = nums.repeat(2);
for (idx, &i) in double.iter().enumerate() {
while !stack.is_empty() && double[*stack.last().unwrap()] < i {
let pos = stack.pop().unwrap();
ans[pos] = i;
}
stack.push(idx);
}
ans.into_iter().take(nums.len()).collect()
}
}
```
<p align="center">

View File

@ -32,9 +32,9 @@ F(n) = F(n - 1) + F(n - 2),其中 n > 1
* 0 <= n <= 30
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[手把手带你入门动态规划 | leetcode509.斐波那契数](https://www.bilibili.com/video/BV1f5411K7mo),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[手把手带你入门动态规划 | leetcode509.斐波那契数](https://www.bilibili.com/video/BV1f5411K7mo),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -278,7 +278,7 @@ class Solution:
return self.fib(n - 1) + self.fib(n - 2)
```
### Go
### Go
```Go
func fib(n int) int {
if n < 2 {
@ -479,3 +479,4 @@ public class Solution
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -20,9 +20,9 @@
![513.找树左下角的值1](https://code-thinking-1253855093.file.myqcloud.com/pics/20210204153017586.png)
## 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[怎么找二叉树的左下角? 递归中又带回溯了,怎么办?| LeetCode513.找二叉树左下角的值](https://www.bilibili.com/video/BV1424y1Z7pn),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[怎么找二叉树的左下角? 递归中又带回溯了,怎么办?| LeetCode513.找二叉树左下角的值](https://www.bilibili.com/video/BV1424y1Z7pn),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -614,7 +614,7 @@ object Solution {
}
```
### rust
### Rust
**层序遍历**
@ -689,3 +689,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -152,8 +152,7 @@ public:
## 其他语言版本
Java
### Java
```java
public class Solution {
@ -175,8 +174,7 @@ public class Solution {
}
```
Python
### Python
```python
class Solution:
@ -193,7 +191,7 @@ class Solution:
return dp[0][-1]
```
Go
### Go
```Go
func longestPalindromeSubseq(s string) int {
@ -222,7 +220,7 @@ func longestPalindromeSubseq(s string) int {
}
```
Javascript
### Javascript
```javascript
const longestPalindromeSubseq = (s) => {
@ -247,7 +245,7 @@ const longestPalindromeSubseq = (s) => {
};
```
TypeScript
### TypeScript
```typescript
function longestPalindromeSubseq(s: string): number {
@ -281,3 +279,4 @@ function longestPalindromeSubseq(s: string): number {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -41,9 +41,9 @@
* 硬币种类不超过 500 种
* 结果符合 32 位符号整数
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[装满背包有多少种方法?组合与排列有讲究!| LeetCode518.零钱兑换II](https://www.bilibili.com/video/BV1KM411k75j/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[装满背包有多少种方法?组合与排列有讲究!| LeetCode518.零钱兑换II](https://www.bilibili.com/video/BV1KM411k75j/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
@ -202,8 +202,8 @@ public:
## 其他语言版本
### Java
Java
```Java
class Solution {
public int change(int amount, int[] coins) {
@ -242,7 +242,7 @@ class Solution {
}
```
Python
### Python
```python
@ -260,7 +260,8 @@ class Solution:
Go
### Go
```go
func change(amount int, coins []int) int {
// 定义dp数组
@ -280,7 +281,8 @@ func change(amount int, coins []int) int {
}
```
Rust:
### Rust:
```rust
impl Solution {
pub fn change(amount: i32, coins: Vec<i32>) -> i32 {
@ -297,7 +299,8 @@ impl Solution {
}
```
Javascript
### Javascript
```javascript
const change = (amount, coins) => {
let dp = Array(amount + 1).fill(0);
@ -313,7 +316,7 @@ const change = (amount, coins) => {
}
```
TypeScript
### TypeScript
```typescript
function change(amount: number, coins: number[]): number {
@ -328,7 +331,7 @@ function change(amount: number, coins: number[]): number {
};
```
Scala:
### Scala:
```scala
object Solution {
@ -349,4 +352,3 @@ object Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -19,12 +19,12 @@
提示:树中至少有 2 个节点。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[二叉搜索树中,需要掌握如何双指针遍历!| LeetCode530.二叉搜索树的最小绝对差](https://www.bilibili.com/video/BV1DD4y11779),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[二叉搜索树中,需要掌握如何双指针遍历!| LeetCode530.二叉搜索树的最小绝对差](https://www.bilibili.com/video/BV1DD4y11779),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
题目中要求在二叉搜索树上任意两节点的差的绝对值的最小值。
@ -32,7 +32,7 @@
遇到在二叉搜索树上求什么最值啊,差值之类的,就把它想成在一个有序数组上求最值,求差值,这样就简单多了。
## 递归
### 递归
那么二叉搜索树采用中序遍历,其实就是一个有序数组。
@ -102,7 +102,7 @@ public:
是不是看上去也并不复杂!
## 迭代
### 迭代
看过这两篇[二叉树:听说递归能做的,栈也能做!](https://programmercarl.com/二叉树的迭代遍历.html)[二叉树:前中后序迭代方式的写法就不能统一一下么?](https://programmercarl.com/二叉树的统一迭代法.html)文章之后,不难写出两种中序遍历的迭代法。
@ -135,7 +135,7 @@ public:
};
```
# 总结
## 总结
**遇到在二叉搜索树上求什么最值,求差值之类的,都要思考一下二叉搜索树可是有序的,要利用好这一特点。**
@ -145,10 +145,10 @@ public:
# 其他语言版本
## 其他语言版本
## Java
### Java
递归
```java
@ -235,7 +235,7 @@ class Solution {
}
}
```
## Python
### Python
递归法(版本一)利用中序递增,结合数组
```python
@ -313,7 +313,7 @@ class Solution:
```
## Go
### Go
中序遍历,然后计算最小差值
```go
@ -340,7 +340,7 @@ func getMinimumDifference(root *TreeNode) int {
}
```
## JavaScript
### JavaScript
递归 先转换为有序数组
```javascript
/**
@ -415,7 +415,7 @@ var getMinimumDifference = function(root) {
}
```
## TypeScript
### TypeScript
> 辅助数组解决
@ -482,7 +482,7 @@ function getMinimumDifference(root: TreeNode | null): number {
};
```
## Scala
### Scala
构建二叉树的有序数组:
@ -561,7 +561,7 @@ object Solution {
}
```
## rust
### Rust
构建二叉树的有序数组:
@ -652,3 +652,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -44,11 +44,11 @@
* 树中的所有值 互不相同 。
* 给定的树为二叉搜索树。
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[普大喜奔!二叉树章节已全部更完啦!| LeetCode538.把二叉搜索树转换为累加树](https://www.bilibili.com/video/BV1d44y1f7wP?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[普大喜奔!二叉树章节已全部更完啦!| LeetCode538.把二叉搜索树转换为累加树](https://www.bilibili.com/video/BV1d44y1f7wP?share_source=copy_web),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
# 思路
## 思路
一看到累加树,相信很多小伙伴都会疑惑:如何累加?遇到一个节点,然后再遍历其他节点累加?怎么一想这么麻烦呢。
@ -64,7 +64,7 @@
那么知道如何遍历这个二叉树,也就迎刃而解了,**从树中可以看出累加的顺序是右中左,所以我们需要反中序遍历这个二叉树,然后顺序累加就可以了**。
## 递归
### 递归
遍历顺序如图所示:
@ -131,7 +131,7 @@ public:
};
```
## 迭代法
### 迭代法
迭代法其实就是中序模板题了,在[二叉树:前中后序迭代法](https://programmercarl.com/二叉树的迭代遍历.html)和[二叉树:前中后序统一方式迭代法](https://programmercarl.com/二叉树的统一迭代法.html)可以选一种自己习惯的写法。
@ -166,17 +166,17 @@ public:
};
```
# 总结
## 总结
经历了前面各种二叉树增删改查的洗礼之后,这道题目应该比较简单了。
**好了,二叉树已经接近尾声了,接下来就是要对二叉树来一个大总结了**。
# 其他语言版本
## 其他语言版本
## Java
### Java
**递归**
```Java
@ -237,7 +237,7 @@ class Solution {
}
```
## Python
### Python
递归法(版本一)
```python
# Definition for a binary tree node.
@ -318,7 +318,7 @@ class Solution:
self.traversal(root)
return root
```
```
迭代法(版本二)
```python
class Solution:
@ -338,9 +338,9 @@ class Solution:
pre = cur.val
cur =cur.left
return root
```
```
## Go
### Go
弄一个sum暂存其和值
```go
@ -362,7 +362,7 @@ func traversal(cur *TreeNode) {
}
```
## JavaScript
### JavaScript
递归
```javascript
@ -401,7 +401,7 @@ var convertBST = function (root) {
};
```
##C
### C
递归
```c
@ -422,7 +422,7 @@ struct TreeNode* convertBST(struct TreeNode* root){
}
```
## TypeScript
### TypeScript
> 递归法
@ -462,7 +462,7 @@ function convertBST(root: TreeNode | null): TreeNode | null {
};
```
## Scala
### Scala
```scala
object Solution {
@ -481,7 +481,7 @@ object Solution {
}
```
## rust
### Rust
递归:
@ -535,3 +535,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -17,9 +17,9 @@
* 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
# 算法公开课
## 算法公开课
**《代码随想录》算法视频公开课:[动态规划之子序列,还是为了编辑距离做铺垫 | LeetCode583.两个字符串的删除操(https://www.bilibili.com/video/BV1we4y157wB/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[LeetCode583.两个字符串的删除操](https://www.bilibili.com/video/BV1we4y157wB/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -143,8 +143,8 @@ public:
## 其他语言版本
### Java
Java
```java
// dp数组中存储word1和word2最长相同子序列的长度
class Solution {
@ -215,8 +215,8 @@ class Solution {
}
```
### Python
Python
```python
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
@ -234,7 +234,8 @@ class Solution:
return dp[-1][-1]
```
Go
### Go
```go
func minDistance(word1 string, word2 string) int {
dp := make([][]int, len(word1)+1)
@ -267,7 +268,8 @@ func min(a, b int) int {
return b
}
```
Javascript
### Javascript
```javascript
// 方法一
var minDistance = (word1, word2) => {
@ -309,7 +311,7 @@ var minDistance = function (word1, word2) {
};
```
TypeScript
### TypeScript
> dp版本一

View File

@ -19,9 +19,9 @@
注意: 合并必须从两个树的根节点开始。
# 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[一起操作两个二叉树?有点懵!| LeetCode617.合并二叉树](https://www.bilibili.com/video/BV1m14y1Y7JK),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[一起操作两个二叉树?有点懵!| LeetCode617.合并二叉树](https://www.bilibili.com/video/BV1m14y1Y7JK),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -164,7 +164,7 @@ public:
};
```
## 迭代法
### 迭代法
使用迭代法,如何同时处理两棵树呢?
@ -716,7 +716,7 @@ object Solution {
}
```
### rust
### Rust
递归:

View File

@ -26,11 +26,13 @@
提示:输入的字符串长度不会超过 1000 。
## 暴力解法
## 思路
### 暴力解法
两层for循环遍历区间起始位置和终止位置然后还需要一层遍历判断这个区间是不是回文。所以时间复杂度O(n^3)
## 动态规划
### 动态规划
动规五部曲:
@ -187,7 +189,7 @@ public:
* 时间复杂度O(n^2)
* 空间复杂度O(n^2)
## 双指针法
### 双指针法
动态规划的空间复杂度是偏高的,我们再看一下双指针法。
@ -231,7 +233,7 @@ public:
## 其他语言版本
Java
### Java
动态规划:
@ -337,7 +339,7 @@ class Solution {
}
```
Python
### Python
> 动态规划:
```python
@ -390,7 +392,8 @@ class Solution:
return res
```
Go
### Go
```Go
func countSubstrings(s string) int {
res:=0
@ -416,7 +419,8 @@ func countSubstrings(s string) int {
}
```
Javascript
### Javascript
> 动态规划
```javascript
const countSubstrings = (s) => {
@ -462,7 +466,7 @@ const countSubstrings = (s) => {
}
```
TypeScript
### TypeScript
> 动态规划:
@ -524,3 +528,4 @@ function expandRange(s: string, left: number, right: number): number {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -42,7 +42,7 @@ Dota2 参议院由来自两派的参议员组成。现在参议院希望对一
因此在第二轮只剩下第三个参议员拥有投票的权利,于是他可以宣布胜利。
# 思路
## 思路
这道题 题意太绕了,我举一个更形象的例子给大家捋顺一下。
@ -70,7 +70,7 @@ Dota2 参议院由来自两派的参议员组成。现在参议院希望对一
如果对贪心算法理论基础还不了解的话,可以看看这篇:[关于贪心算法,你该了解这些!](https://programmercarl.com/贪心算法理论基础.html) ,相信看完之后对贪心就有基本的了解了。
# 代码实现
## 代码实现
实现代码,在每一轮循环的过程中,去过模拟优先消灭身后的对手,其实是比较麻烦的。
@ -111,9 +111,9 @@ public:
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
class Solution {
@ -145,7 +145,7 @@ class Solution {
}
```
## Python
### Python
```python
class Solution:
@ -173,7 +173,7 @@ class Solution:
return "Radiant" if R else "Dire"
```
## Go
### Go
```go
@ -214,7 +214,7 @@ func predictPartyVictory(senateStr string) string {
}
```
## JavaScript
### JavaScript
```js
var predictPartyVictory = function(senateStr) {
@ -244,7 +244,7 @@ var predictPartyVictory = function(senateStr) {
};
```
## TypeScript
### TypeScript
```typescript
function predictPartyVictory(senate: string): string {
@ -287,3 +287,4 @@ function predictPartyVictory(senate: string): string {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -25,9 +25,9 @@
给定的数组的大小在 [1, 1000] 之间。
## 视频讲解
## 算法公开课
**《代码随想录》算法视频公开课:[又是构造二叉树,又有很多坑!| LeetCode654.最大二叉树](https://www.bilibili.com/video/BV1MG411G7ox),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)[又是构造二叉树,又有很多坑!| LeetCode654.最大二叉树](https://www.bilibili.com/video/BV1MG411G7ox),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
## 思路
@ -310,7 +310,7 @@ class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
return self.traversal(nums, 0, len(nums))
```
```
(版本三) 使用切片
@ -587,3 +587,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -29,7 +29,7 @@
# 思路
## 思路
这道题目还是挺简单的,大家不要想复杂了,一波哈希法又一波图论算法啥的,哈哈。
@ -64,9 +64,9 @@ public:
```
# 其他语言版本
## 其他语言版本
## Java
### Java
```java
// 时间复杂度O(n)
@ -86,7 +86,7 @@ class Solution {
}
```
## Python
### Python
```python
# 时间复杂度O(n)
@ -107,7 +107,7 @@ class Solution:
return x == 0 and y == 0
```
## Go
### Go
```go
func judgeCircle(moves string) bool {
@ -131,7 +131,7 @@ func judgeCircle(moves string) bool {
}
```
## JavaScript
### JavaScript
```js
// 时间复杂度O(n)
@ -150,7 +150,7 @@ var judgeCircle = function(moves) {
```
## TypeScript
### TypeScript
```ts
var judgeCircle = function (moves) {
@ -185,3 +185,4 @@ var judgeCircle = function (moves) {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

Some files were not shown because too many files have changed in this diff Show More