From 4b575a8dab798fc213c56d21891e6d6e7446bbc5 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+fwqaaq@users.noreply.github.com> Date: Wed, 7 Dec 2022 23:18:23 +0800 Subject: [PATCH 01/92] =?UTF-8?q?Update=200450.=E5=88=A0=E9=99=A4=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0450.删除二叉搜索树中的节点.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 0b4048d5..3d9a6050 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -657,6 +657,39 @@ object Solution { } ``` +## rust + +```rust +impl Solution { + pub fn delete_node( + root: Option>>, + key: i32, + ) -> Option>> { + root.as_ref()?; + + let mut node = root.as_ref().unwrap().borrow_mut(); + match node.val.cmp(&key) { + std::cmp::Ordering::Less => node.right = Self::delete_node(node.right.clone(), key), + std::cmp::Ordering::Equal => match (node.left.clone(), node.right.clone()) { + (None, None) => return None, + (None, Some(r)) => return Some(r), + (Some(l), None) => return Some(l), + (Some(l), Some(r)) => { + let mut cur = Some(r.clone()); + while let Some(n) = cur.clone().unwrap().borrow().left.clone() { + cur = Some(n); + } + cur.unwrap().borrow_mut().left = Some(l); + return Some(r); + } + }, + std::cmp::Ordering::Greater => node.left = Self::delete_node(node.left.clone(), key), + } + root.clone() + } +} +``` +

From d97f27621c96972c11b0e48b5498c411ac1e85f5 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+fwqaaq@users.noreply.github.com> Date: Fri, 9 Dec 2022 15:44:18 +0800 Subject: [PATCH 02/92] =?UTF-8?q?Update=20problems/0450.=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0450.删除二叉搜索树中的节点.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 3d9a6050..424491b7 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -685,7 +685,8 @@ impl Solution { }, std::cmp::Ordering::Greater => node.left = Self::delete_node(node.left.clone(), key), } - root.clone() + drop(node); + root } } ``` From 3dda10b12f589a78fb026ef469c788415901b7cd Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Fri, 10 Mar 2023 14:11:11 +0800 Subject: [PATCH 03/92] Update --- problems/0377.组合总和IV二维dp数组.md | 145 ------------------ 1 file changed, 145 deletions(-) delete mode 100644 problems/0377.组合总和IV二维dp数组.md diff --git a/problems/0377.组合总和IV二维dp数组.md b/problems/0377.组合总和IV二维dp数组.md deleted file mode 100644 index 276329c5..00000000 --- a/problems/0377.组合总和IV二维dp数组.md +++ /dev/null @@ -1,145 +0,0 @@ -# 完全背包的排列问题模拟 - -#### Problem - -1. 排列问题是完全背包中十分棘手的问题。 -2. 其在迭代过程中需要先迭代背包容量,再迭代物品个数,使得其在代码理解上较难入手。 - -#### Contribution - -本文档以力扣上[组合总和IV](https://leetcode.cn/problems/combination-sum-iv/)为例,提供一个二维dp的代码例子,并提供模拟过程以便于理解 - -#### Code - -```cpp -int combinationSum4(vector& nums, int target) { - // 定义背包容量为target,物品个数为nums.size()的dp数组 - // dp[i][j]表示将第0-i个物品添加入排列中,和为j的排列方式 - vector> dp (nums.size(), vector(target+1,0)); - - // 表示有0,1,...,n个物品可选择的情况下,和为0的选择方法为1:什么都不取 - for(int i = 0; i < nums.size(); i++) dp[i][0] = 1; - - // 必须按列遍历,因为右边数组需要知道左边数组最低部的信息(排列问题) - // 后面的模拟可以更清楚的表现这么操作的原因 - for(int i = 1; i <= target; i++){ - for(int j = 0; j < nums.size(); j++){ - // 只有nums[j]可以取的情况 - if(j == 0){ - if(nums[j] > i) dp[j][i] = 0; - // 如果背包容量放不下 那么此时没有排列方式 - else dp[j][i] = dp[nums.size()-1][i-nums[j]]; - // 如果背包容量放的下 全排列方式为dp[最底层][容量-该物品容量]排列方式后面放一个nums[j] - } - // 有多个nums数可以取 - else{ - // 如果背包容量放不下 那么沿用0-j-1个物品的排列方式 - if(nums[j] > i) dp[j][i] = dp[j-1][i]; - // 如果背包容量放得下 在dp[最底层][容量-该物品容量]排列方式后面放一个nums[j]后面放个nums[j] - // INT_MAX避免溢出 - else if(i >= nums[j] && dp[j-1][i] < INT_MAX - dp[nums.size()-1][i-nums[j]]) - dp[j][i] = dp[j-1][i] + dp[nums.size()-1][i-nums[j]]; - } - } - } - // 打印dp数组 - for(int i = 0; i < nums.size(); i++){ - for(int j = 0; j <= target; j++){ - cout< Date: Sun, 19 Mar 2023 11:13:54 +0800 Subject: [PATCH 04/92] =?UTF-8?q?Update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 还有 --> 还要 --- problems/0001.两数之和.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index a0acdcbe..a8f8bf17 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -41,7 +41,7 @@ 那么我们就应该想到使用哈希法了。 -因为本地,我们不仅要知道元素有没有遍历过,还有知道这个元素对应的下标,**需要使用 key value结构来存放,key来存元素,value来存下标,那么使用map正合适**。 +因为本地,我们不仅要知道元素有没有遍历过,还要知道这个元素对应的下标,**需要使用 key value结构来存放,key来存元素,value来存下标,那么使用map正合适**。 再来看一下使用数组和set来做哈希法的局限。 From 633cb549fb21c4f45a366a973dcc30768a97a03f Mon Sep 17 00:00:00 2001 From: Javie Deng Date: Mon, 20 Mar 2023 12:36:06 +0800 Subject: [PATCH 05/92] =?UTF-8?q?=E4=B8=BA0226.=E7=BF=BB=E8=BD=AC=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E6=B7=BB=E5=8A=A0=E4=BA=86C#=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E7=89=88=EF=BC=88=E5=8C=85=E5=90=AB=E9=80=92=E5=BD=92?= =?UTF-8?q?=E5=92=8C=E8=BF=AD=E4=BB=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 47 ++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 16a5be57..611e971a 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -914,6 +914,53 @@ impl Solution { } ``` +### C# + +```csharp +//递归 +public class Solution { + public TreeNode InvertTree(TreeNode root) { + if (root == null) return root; + + swap(root); + InvertTree(root.left); + InvertTree(root.right); + return root; + } + + public void swap(TreeNode node) { + TreeNode temp = node.left; + node.left = node.right; + node.right = temp; + } +} +``` + +```csharp +//迭代 +public class Solution { + public TreeNode InvertTree(TreeNode root) { + if (root == null) return null; + Stack stack=new Stack(); + stack.Push(root); + while(stack.Count>0) + { + TreeNode node = stack.Pop(); + swap(node); + if(node.right!=null) stack.Push(node.right); + if(node.left!=null) stack.Push(node.left); + } + return root; + } + + public void swap(TreeNode node) { + TreeNode temp = node.left; + node.left = node.right; + node.right = temp; + } +} +``` +

From da2acd7dcf6c0a3fde44bb3801395eb7050f19f3 Mon Sep 17 00:00:00 2001 From: Javie Deng Date: Mon, 20 Mar 2023 13:05:00 +0800 Subject: [PATCH 06/92] =?UTF-8?q?"=E4=B8=BA0226.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E6=B7=BB=E5=8A=A0=E4=BA=86C#?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E7=89=88=EF=BC=88=E5=8C=85=E5=90=AB=E9=80=92?= =?UTF-8?q?=E5=BD=92=E5=92=8C=E8=BF=AD=E4=BB=A3=EF=BC=89"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 611e971a..c1f0f2c1 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -928,7 +928,7 @@ public class Solution { return root; } - public void swap(TreeNode node) { + public void swap(TreeNode node) { TreeNode temp = node.left; node.left = node.right; node.right = temp; @@ -953,7 +953,7 @@ public class Solution { return root; } - public void swap(TreeNode node) { + public void swap(TreeNode node) { TreeNode temp = node.left; node.left = node.right; node.right = temp; From f51f31290f69bf467bdb444d8c85a94b0c30616a Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 23 Mar 2023 11:10:20 +0800 Subject: [PATCH 07/92] =?UTF-8?q?Update=200406.=E6=A0=B9=E6=8D=AE=E8=BA=AB?= =?UTF-8?q?=E9=AB=98=E9=87=8D=E5=BB=BA=E9=98=9F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0406.根据身高重建队列.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/problems/0406.根据身高重建队列.md b/problems/0406.根据身高重建队列.md index 48c498e1..2e6818db 100644 --- a/problems/0406.根据身高重建队列.md +++ b/problems/0406.根据身高重建队列.md @@ -291,19 +291,19 @@ var reconstructQueue = function(people) { ```Rust impl Solution { - pub fn reconstruct_queue(people: Vec>) -> Vec> { - let mut people = people; + pub fn reconstruct_queue(mut people: Vec>) -> Vec> { + let mut queue = vec![]; people.sort_by(|a, b| { - if a[0] == b[0] { return a[1].cmp(&b[1]); } + if a[0] == b[0] { + return a[1].cmp(&b[1]); + } b[0].cmp(&a[0]) }); - let mut que: Vec> = Vec::new(); - que.push(people[0].clone()); - for i in 1..people.len() { - let position = people[i][1]; - que.insert(position as usize, people[i].clone()); + queue.push(people[0].clone()); + for v in people.iter().skip(1) { + queue.insert(v[1] as usize, v.clone()); } - que + queue } } ``` From b934f47c83340b91b8a6291d96420978da0ec0e6 Mon Sep 17 00:00:00 2001 From: milu-tao <91822069+milu-tao@users.noreply.github.com> Date: Fri, 24 Mar 2023 22:14:39 +0800 Subject: [PATCH 08/92] =?UTF-8?q?Update=200647.=E5=9B=9E=E6=96=87=E5=AD=90?= =?UTF-8?q?=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. result 在遍历过程中 ++ 就行,没必要另外计算 2.题目已经表明:s字符串的长度规则是:1 <= s.length <= 1000,所以前面不需要进行判断字符串长度 --- problems/0647.回文子串.md | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 90e6da9f..339247f5 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -238,33 +238,24 @@ Java: ```java class Solution { public int countSubstrings(String s) { - int len, ans = 0; - if (s == null || (len = s.length()) < 1) return 0; - //dp[i][j]:s字符串下标i到下标j的字串是否是一个回文串,即s[i, j] + char[] chars = s.toCharArray(); + int len = chars.length; boolean[][] dp = new boolean[len][len]; - for (int j = 0; j < len; j++) { - for (int i = 0; i <= j; i++) { - //当两端字母一样时,才可以两端收缩进一步判断 - if (s.charAt(i) == s.charAt(j)) { - //i++,j--,即两端收缩之后i,j指针指向同一个字符或者i超过j了,必然是一个回文串 - if (j - i < 3) { + int result = 0; + for (int i = len - 1; i >= 0; i--) { + for (int j = i; j < len; j++) { + if (chars[i] == chars[j]) { + if (j - i <= 1) { // 情况一 和 情况二 + result++; + dp[i][j] = true; + } else if (dp[i + 1][j - 1]) { //情况三 + result++; dp[i][j] = true; - } else { - //否则通过收缩之后的字串判断 - dp[i][j] = dp[i + 1][j - 1]; } - } else {//两端字符不一样,不是回文串 - dp[i][j] = false; } } } - //遍历每一个字串,统计回文串个数 - for (int i = 0; i < len; i++) { - for (int j = 0; j < len; j++) { - if (dp[i][j]) ans++; - } - } - return ans; + return result; } } ``` From dad45d599b9368e7ddeeea9b62bc53bea122fc24 Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Wed, 29 Mar 2023 11:34:59 +0800 Subject: [PATCH 09/92] Update --- README.md | 2 +- ...包的排列问题二维迭代理解).md | 145 ------------------ ...一讲递归算法的时间复杂度!.md | 16 +- problems/哈希表理论基础.md | 5 +- 4 files changed, 11 insertions(+), 157 deletions(-) delete mode 100644 problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md diff --git a/README.md b/README.md index a9b2f7ef..f3e5812c 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ 如果你是算法老手,这篇攻略也是复习的最佳资料,如果把每个系列对应的总结篇,快速过一遍,整个算法知识体系以及各种解法就重现脑海了。 -目前「代码随想录」刷题攻略更新了:**200多篇文章,精讲了200道经典算法题目,共60w字的详细图解,部分难点题目还搭配了20分钟左右的视频讲解**。 +目前「代码随想录」刷题攻略更新了:**200多篇文章,精讲了200道经典算法题目,共60w字的详细图解,大部分题目都搭配了20分钟左右的视频讲解**,视频质量很好,口碑很好,大家可以去看看,视频列表:[代码随想录视频讲解](https://www.bilibili.com/video/BV1fA4y1o715)。 **这里每一篇题解,都是精品,值得仔细琢磨**。 diff --git a/problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md b/problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md deleted file mode 100644 index 276329c5..00000000 --- a/problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md +++ /dev/null @@ -1,145 +0,0 @@ -# 完全背包的排列问题模拟 - -#### Problem - -1. 排列问题是完全背包中十分棘手的问题。 -2. 其在迭代过程中需要先迭代背包容量,再迭代物品个数,使得其在代码理解上较难入手。 - -#### Contribution - -本文档以力扣上[组合总和IV](https://leetcode.cn/problems/combination-sum-iv/)为例,提供一个二维dp的代码例子,并提供模拟过程以便于理解 - -#### Code - -```cpp -int combinationSum4(vector& nums, int target) { - // 定义背包容量为target,物品个数为nums.size()的dp数组 - // dp[i][j]表示将第0-i个物品添加入排列中,和为j的排列方式 - vector> dp (nums.size(), vector(target+1,0)); - - // 表示有0,1,...,n个物品可选择的情况下,和为0的选择方法为1:什么都不取 - for(int i = 0; i < nums.size(); i++) dp[i][0] = 1; - - // 必须按列遍历,因为右边数组需要知道左边数组最低部的信息(排列问题) - // 后面的模拟可以更清楚的表现这么操作的原因 - for(int i = 1; i <= target; i++){ - for(int j = 0; j < nums.size(); j++){ - // 只有nums[j]可以取的情况 - if(j == 0){ - if(nums[j] > i) dp[j][i] = 0; - // 如果背包容量放不下 那么此时没有排列方式 - else dp[j][i] = dp[nums.size()-1][i-nums[j]]; - // 如果背包容量放的下 全排列方式为dp[最底层][容量-该物品容量]排列方式后面放一个nums[j] - } - // 有多个nums数可以取 - else{ - // 如果背包容量放不下 那么沿用0-j-1个物品的排列方式 - if(nums[j] > i) dp[j][i] = dp[j-1][i]; - // 如果背包容量放得下 在dp[最底层][容量-该物品容量]排列方式后面放一个nums[j]后面放个nums[j] - // INT_MAX避免溢出 - else if(i >= nums[j] && dp[j-1][i] < INT_MAX - dp[nums.size()-1][i-nums[j]]) - dp[j][i] = dp[j-1][i] + dp[nums.size()-1][i-nums[j]]; - } - } - } - // 打印dp数组 - for(int i = 0; i < nums.size(); i++){ - for(int j = 0; j <= target; j++){ - cout< Date: Wed, 29 Mar 2023 22:47:54 -0400 Subject: [PATCH 10/92] =?UTF-8?q?Update=200225.=E7=94=A8=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=A0=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增一個java solution用的是卡哥的邏輯 --- problems/0225.用队列实现栈.md | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 16b9e47c..66d807c1 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -324,6 +324,43 @@ class MyStack { } } +``` +优化,使用一个 Queue 实现,但用卡哥的逻辑实现 +``` +class MyStack { + Queue queue; + + public MyStack() { + queue = new LinkedList<>(); + } + + public void push(int x) { + queue.add(x); + } + + public int pop() { + rePosition(); + return queue.poll(); + } + + public int top() { + rePosition(); + int result = queue.poll(); + queue.add(result); + return result; + } + + public boolean empty() { + return queue.isEmpty(); + } + + public void rePosition(){ + int size = queue.size(); + size--; + while(size-->0) + queue.add(queue.poll()); + } +} ``` Python: From 1d74967090ff2adf96d84ba7f4dbd81d0ed53e68 Mon Sep 17 00:00:00 2001 From: Logen <47022821+Logenleedev@users.noreply.github.com> Date: Thu, 6 Apr 2023 13:40:06 -0500 Subject: [PATCH 11/92] fix typos --- problems/0376.摆动序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 469c19fd..26baf2f9 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -99,7 +99,7 @@ 这里我们可以写死,就是 如果只有两个元素,且元素不同,那么结果为 2。 -不写死的话,如果和我们的判断规则结合在一起呢? +不写死的话,如何和我们的判断规则结合在一起呢? 可以假设,数组最前面还有一个数字,那这个数字应该是什么呢? From dee25873fc8f594dbc0209453399669df5fdf61a Mon Sep 17 00:00:00 2001 From: Levi <3573897471@qq.com> Date: Fri, 7 Apr 2023 17:05:31 +0800 Subject: [PATCH 12/92] =?UTF-8?q?=E8=A1=A5=E5=85=850111.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E5=85=B3=E4=BA=8E=E5=89=8D=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?=EF=BC=88=E4=B8=AD=E5=B7=A6=E5=8F=B3=EF=BC=89=E7=9A=84=E4=B8=AD?= =?UTF-8?q?=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index de36c6f2..47569b05 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -170,11 +170,14 @@ class Solution { private: int result; void getdepth(TreeNode* node, int depth) { - if (node->left == NULL && node->right == NULL) { - result = min(depth, result); + // 函数递归终止条件 + if (root == nullptr) { return; } - // 中 只不过中没有处理的逻辑 + // 中,处理逻辑:判断是不是叶子结点 + if (root -> left == nullptr && root->right == nullptr) { + res = min(res, depth); + } if (node->left) { // 左 getdepth(node->left, depth + 1); } @@ -186,7 +189,9 @@ private: public: int minDepth(TreeNode* root) { - if (root == NULL) return 0; + if (root == nullptr) { + return 0; + } result = INT_MAX; getdepth(root, 1); return result; From e68a8a379be1defd7952a0d87fcac4350363de13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8A=B1=E6=97=A0=E7=BC=BA?= Date: Sun, 9 Apr 2023 14:54:51 +0800 Subject: [PATCH 13/92] =?UTF-8?q?update=20=E4=B8=8D=E5=90=8C=E8=B7=AF?= =?UTF-8?q?=E5=BE=84II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更正文档错别字 --- problems/0063.不同路径II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 85130ab4..62210420 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -135,7 +135,7 @@ for (int i = 1; i < m; i++) { ![63.不同路径II2](https://code-thinking-1253855093.file.myqcloud.com/pics/20210104114610256.png) -如果这个图看不同,建议在理解一下递归公式,然后照着文章中说的遍历顺序,自己推导一下! +如果这个图看不懂,建议再理解一下递归公式,然后照着文章中说的遍历顺序,自己推导一下! 动规五部分分析完毕,对应C++代码如下: From e1e695e78d3fbba5ebf01fe1be69c6569f9a035a Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Sun, 9 Apr 2023 23:11:11 +0800 Subject: [PATCH 14/92] =?UTF-8?q?Update=200509.=E6=96=90=E6=B3=A2=E9=82=A3?= =?UTF-8?q?=E5=A5=91=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0509.斐波那契数.md | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 08175058..479b36a0 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -347,26 +347,32 @@ int fib(int n){ ### Rust 动态规划: ```Rust -pub fn fib(n: i32) -> i32 { - let n = n as usize; - let mut dp = vec![0; 31]; - dp[1] = 1; - for i in 2..=n { - dp[i] = dp[i - 1] + dp[i - 2]; +impl Solution { + pub fn fib(n: i32) -> i32 { + if n <= 1 { + return n; + } + let n = n as usize; + let mut dp = vec![0; n + 1]; + dp[1] = 1; + for i in 2..=n { + dp[i] = dp[i - 2] + dp[i - 1]; + } + dp[n] } - dp[n] } ``` 递归实现: ```Rust -pub fn fib(n: i32) -> i32 { - //若n小于等于1,返回n - f n <= 1 { - return n; +impl Solution { + pub fn fib(n: i32) -> i32 { + if n <= 1 { + n + } else { + Self::fib(n - 1) + Self::fib(n - 2) + } } - //否则返回fib(n-1) + fib(n-2) - return fib(n - 1) + fib(n - 2); } ``` From 185f6df9d8dbad3c67724bdaa97b6fa307b5b9e1 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Sun, 9 Apr 2023 17:25:58 -0400 Subject: [PATCH 15/92] =?UTF-8?q?Update=2020210204=E5=8A=A8=E8=A7=84?= =?UTF-8?q?=E5=91=A8=E6=9C=AB=E6=80=BB=E7=BB=93.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改错别字: 原为:先遍历物品,在遍历背包 改为:先遍历物品,再遍历背包 --- problems/周总结/20210204动规周末总结.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/周总结/20210204动规周末总结.md b/problems/周总结/20210204动规周末总结.md index 9a64c152..fb570bd4 100644 --- a/problems/周总结/20210204动规周末总结.md +++ b/problems/周总结/20210204动规周末总结.md @@ -146,7 +146,7 @@ public: **这也体现了刷题顺序的重要性**。 -先遍历背包,在遍历物品: +先遍历背包,再遍历物品: ```CPP // 版本一 @@ -165,7 +165,7 @@ public: }; ``` -先遍历物品,在遍历背包: +先遍历物品,再遍历背包: ```CPP // 版本二 From 2be03e614ddaa09b11b7bae3de7fddd99b959a92 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Sun, 9 Apr 2023 18:07:43 -0400 Subject: [PATCH 16/92] =?UTF-8?q?Update=200139.=E5=8D=95=E8=AF=8D=E6=8B=86?= =?UTF-8?q?=E5=88=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加:python - 和视频中写法一致(和最上面C++写法一致) --- problems/0139.单词拆分.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index edb2c65a..230942ef 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -351,7 +351,17 @@ class Solution: dp[j] = dp[j] or (dp[j - len(word)] and word == s[j - len(word):j]) return dp[len(s)] ``` - +```python +class Solution: # 和视频中写法一致(和最上面C++写法一致) + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + dp = [False]*(len(s)+1) + dp[0]=True + for j in range(1,len(s)+1): + for i in range(j): + word = s[i:j] + if word in wordDict and dp[i]: dp[j]=True + return dp[-1] +``` From 962744515d4e67a417dc0f87ffda90710b974a76 Mon Sep 17 00:00:00 2001 From: "435962415@qq.com" Date: Mon, 10 Apr 2023 11:59:08 +0800 Subject: [PATCH 17/92] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=860188.=E4=B9=B0?= =?UTF-8?q?=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6?= =?UTF-8?q?=E6=9C=BAIV=E7=9A=84=E8=A7=A3=E6=B3=95=E4=BA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 4fdd7bf4..77d1c961 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -323,6 +323,42 @@ func max(a, b int) int { } ``` +版本二: 三维 dp数组 +```go +func maxProfit(k int, prices []int) int { + length := len(prices) + if length == 0 { + return 0 + } + // [天数][交易次数][是否持有股票] + // 1表示不持有/卖出, 0表示持有/买入 + dp := make([][][]int, length) + for i := 0; i < length; i++ { + dp[i] = make([][]int, k+1) + for j := 0; j <= k; j++ { + dp[i][j] = make([]int, 2) + } + } + for j := 0; j <= k; j++ { + dp[0][j][0] = -prices[0] + } + for i := 1; i < length; i++ { + for j := 1; j <= k; j++ { + dp[i][j][0] = max188(dp[i-1][j][0], dp[i-1][j-1][1]-prices[i]) + dp[i][j][1] = max188(dp[i-1][j][1], dp[i-1][j][0]+prices[i]) + } + } + return dp[length-1][k][1] +} + +func max188(a, b int) int { + if a > b { + return a + } + return b +} +``` + Javascript: ```javascript From 801e03ab3112da8e3e1666fafded4aa998836723 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Mon, 10 Apr 2023 00:48:03 -0400 Subject: [PATCH 18/92] =?UTF-8?q?Update=200198.=E6=89=93=E5=AE=B6=E5=8A=AB?= =?UTF-8?q?=E8=88=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加python - 二维dp数组写法 --- problems/0198.打家劫舍.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index fdb2dabf..20e18c08 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -150,7 +150,17 @@ class Solution: dp[i] = max(dp[i-2]+nums[i], dp[i-1]) return dp[-1] ``` - +```python +class Solution: # 二维dp数组写法 + def rob(self, nums: List[int]) -> int: + dp = [[0,0] for _ in range(len(nums))] + dp[0][1] = nums[0] + for i in range(1,len(nums)): + dp[i][0] = max(dp[i-1][1],dp[i-1][0]) + dp[i][1] = dp[i-1][0]+nums[i] + print(dp) + return max(dp[-1]) +``` Go: ```Go func rob(nums []int) int { From 34aabac5b93af8dcb2e56a48c8f1b9049f2a28be Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Mon, 10 Apr 2023 00:58:56 -0400 Subject: [PATCH 19/92] =?UTF-8?q?Update=200213.=E6=89=93=E5=AE=B6=E5=8A=AB?= =?UTF-8?q?=E8=88=8DII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加python - 二维dp数组写法 --- problems/0213.打家劫舍II.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index 0627eedb..5d315d5c 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -142,7 +142,20 @@ class Solution: dp[i]=max(dp[i-1],dp[i-2]+nums[i]) return dp[-1] ``` - +```python +class Solution: # 二维dp数组写法 + def rob(self, nums: List[int]) -> int: + if len(nums)<3: return max(nums) + return max(self.default(nums[:-1]),self.default(nums[1:])) + def default(self,nums): + dp = [[0,0] for _ in range(len(nums))] + dp[0][1] = nums[0] + for i in range(1,len(nums)): + dp[i][0] = max(dp[i-1]) + dp[i][1] = dp[i-1][0] + nums[i] + return max(dp[-1]) + +``` Go: ```go From abbcbe1ed0b52b7232957bf9152ad0e92104114d Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Mon, 10 Apr 2023 15:28:58 +0800 Subject: [PATCH 20/92] =?UTF-8?q?Update=200070.=E7=88=AC=E6=A5=BC=E6=A2=AF?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0070.爬楼梯.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index a06ee91e..c46e3b46 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -470,6 +470,23 @@ impl Solution { } ``` +dp 数组 + +```rust +impl Solution { + pub fn climb_stairs(n: i32) -> i32 { + let n = n as usize; + let mut dp = vec![0; n + 1]; + dp[0] = 1; + dp[1] = 1; + for i in 2..=n { + dp[i] = dp[i - 1] + dp[i - 2]; + } + dp[n] + } +} +``` +

From 03f037afebff9684e9d64283b1d8d5ec690e684a Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Mon, 10 Apr 2023 15:36:23 +0800 Subject: [PATCH 21/92] =?UTF-8?q?Update=200070.=E7=88=AC=E6=A5=BC=E6=A2=AF?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0070.爬楼梯.md | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index c46e3b46..793d3e67 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -454,19 +454,16 @@ public class Solution { ```rust impl Solution { pub fn climb_stairs(n: i32) -> i32 { - if n <= 2 { + if n <= 1 { return n; } - let mut a = 1; - let mut b = 2; - let mut f = 0; - for i in 2..n { + let (mut a, mut b, mut f) = (1, 1, 0); + for _ in 2..=n { f = a + b; a = b; b = f; } - return f; - } + f } ``` From 8f58ab445a4f7a50a0a9d3ab9c2041dba0c1f2d9 Mon Sep 17 00:00:00 2001 From: Erincrying <1016158928@qq.com> Date: Tue, 11 Apr 2023 20:20:33 +0800 Subject: [PATCH 22/92] =?UTF-8?q?=E6=9B=B4=E6=96=B0242.=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D=EF=BC=8C?= =?UTF-8?q?js=E6=96=B9=E6=B3=95=EF=BC=8C=E9=87=87=E7=94=A8map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0242.有效的字母异位词.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 1006ea35..ba802bbd 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -205,6 +205,19 @@ var isAnagram = function(s, t) { } return true; }; + +var isAnagram = function(s, t) { + if(s.length !== t.length) return false; + let char_count = new Map(); + for(let item of s) { + char_count.set(item, (char_count.get(item) || 0) + 1) ; + } + for(let item of t) { + if(!char_count.get(item)) return false; + char_count.set(item, char_count.get(item)-1); + } + return true; +}; ``` TypeScript: From eef44eb9e82c6f8c605e4e2575a3200dafe0014d Mon Sep 17 00:00:00 2001 From: Erincrying <1016158928@qq.com> Date: Tue, 11 Apr 2023 21:26:44 +0800 Subject: [PATCH 23/92] =?UTF-8?q?=E6=9B=B4=E6=96=B01002.=20=E6=9F=A5?= =?UTF-8?q?=E6=89=BE=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6=EF=BC=8Cjs?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E9=87=87=E7=94=A8map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index fd188660..9ec3c6c4 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -252,6 +252,36 @@ var commonChars = function (words) { } return res }; + +// 方法二:map() +var commonChars = function(words) { + let min_count = new Map() + // 统计字符串中字符出现的最小频率,以第一个字符串初始化 + for(let str of words[0]) { + min_count.set(str, ((min_count.get(str) || 0) + 1)) + } + // 从第二个单词开始统计字符出现次数 + for(let i = 1; i < words.length; i++) { + let char_count = new Map() + for(let str of words[i]) { // 遍历字母 + char_count.set(str, (char_count.get(str) || 0) + 1) + } + // 比较出最小的字符次数 + for(let value of min_count) { // 注意这里遍历min_count!而不是单词 + min_count.set(value[0], Math.min((min_count.get(value[0]) || 0), (char_count.get(value[0]) || 0))) + } + } + // 遍历map + let res = [] + min_count.forEach((value, key) => { + if(value) { + for(let i=0; i Date: Thu, 13 Apr 2023 12:20:18 +0800 Subject: [PATCH 24/92] =?UTF-8?q?Update=200746.=E4=BD=BF=E7=94=A8=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 28 ++++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index d7258d45..98a58c12 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -351,17 +351,29 @@ function minCostClimbingStairs(cost: number[]): number { ### Rust ```Rust -use std::cmp::min; impl Solution { pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { - let len = cost.len(); - let mut dp = vec![0; len]; - dp[0] = cost[0]; - dp[1] = cost[1]; - for i in 2..len { - dp[i] = min(dp[i-1], dp[i-2]) + cost[i]; + let mut dp = vec![0; cost.len() + 1]; + for i in 2..=cost.len() { + dp[i] = (dp[i - 1] + cost[i - 1]).min(dp[i - 2] + cost[i - 2]); } - min(dp[len-1], dp[len-2]) + dp[cost.len()] + } +} +``` + +不使用 dp 数组 + +```rust +impl Solution { + pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { + let (mut dp_before, mut dp_after) = (0, 0); + for i in 2..=cost.len() { + let dpi = (dp_before + cost[i - 2]).min(dp_after + cost[i - 1]); + dp_before = dp_after; + dp_after = dpi; + } + dp_after } } ``` From e9c4d54f537a1c42f71b5651bfc4baa0cd1a51e8 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 12:28:51 +0800 Subject: [PATCH 25/92] =?UTF-8?q?Update=200746.=E4=BD=BF=E7=94=A8=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 37 +++++++++++--------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 98a58c12..3d014858 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -330,22 +330,27 @@ var minCostClimbingStairs = function(cost) { ```typescript function minCostClimbingStairs(cost: number[]): number { - /** - dp[i]: 走到第i阶需要花费的最少金钱 - dp[0]: 0; - dp[1]: 0; - ... - dp[i]: min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); - */ - const dp = []; - const length = cost.length; - dp[0] = 0; - dp[1] = 0; - for (let i = 2; i <= length; i++) { - dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); - } - return dp[length]; -}; + const dp = [0, 0] + for (let i = 2; i <= cost.length; i++) { + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + } + return dp[cost.length] +} +``` + +不使用 dp 数组 + +```typescript +function minCostClimbingStairs(cost: number[]): number { + let dp_before = 0, + dp_after = 0 + for (let i = 2; i <= cost.length; i++) { + let dpi = Math.min(dp_before + cost[i - 2], dp_after + cost[i - 1]) + dp_before = dp_after + dp_after = dpi + } + return dp_after +} ``` ### Rust From 1ad26f69cdffc20bec0c95669e929dab0f7d3b2c Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 12:37:03 +0800 Subject: [PATCH 26/92] =?UTF-8?q?Update=200746.=E4=BD=BF=E7=94=A8=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 41 +++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 3d014858..fb5261f3 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -312,17 +312,30 @@ func min(a, b int) int { ``` -### Javascript +### JavaScript + ```Javascript var minCostClimbingStairs = function(cost) { - const n = cost.length; - const dp = new Array(n + 1); - dp[0] = dp[1] = 0; - for (let i = 2; i <= n; ++i) { - dp[i] = Math.min(dp[i -1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + const dp = [0, 0] + for (let i = 2; i <= cost.length; ++i) { + dp[i] = Math.min(dp[i -1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + } + return dp[cost.length] +}; +``` + +不使用 dp 数组 + +```JavaScript +var minCostClimbingStairs = function(cost) { + let dpBefore = 0, + dpAfter = 0 + for(let i = 2;i <= cost.length;i++){ + let dpi = Math.min(dpBefore + cost[i - 2],dpAfter + cost[i - 1]) + dpBefore = dpAfter + dpAfter = dpi } - - return dp[n] + return dpAfter }; ``` @@ -342,14 +355,14 @@ function minCostClimbingStairs(cost: number[]): number { ```typescript function minCostClimbingStairs(cost: number[]): number { - let dp_before = 0, - dp_after = 0 + let dpBefore = 0, + dpAfter = 0 for (let i = 2; i <= cost.length; i++) { - let dpi = Math.min(dp_before + cost[i - 2], dp_after + cost[i - 1]) - dp_before = dp_after - dp_after = dpi + let dpi = Math.min(dpBefore + cost[i - 2], dpAfter + cost[i - 1]) + dpBefore = dpAfter + dpAfter = dpi } - return dp_after + return dpAfter } ``` From ac16522a48d90d45d2f87f50a2c336fc383f4134 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 12:37:46 +0800 Subject: [PATCH 27/92] =?UTF-8?q?Update=20problems/0746.=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=9C=80=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index fb5261f3..561441fc 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -314,7 +314,7 @@ func min(a, b int) int { ### JavaScript -```Javascript +```JavaScript var minCostClimbingStairs = function(cost) { const dp = [0, 0] for (let i = 2; i <= cost.length; ++i) { From 057d6b8f89ea5bbef1bb460ce40d9093abd1c3e0 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 13:34:46 +0800 Subject: [PATCH 28/92] =?UTF-8?q?Update=200746.=E4=BD=BF=E7=94=A8=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 33 +++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 561441fc..f11439c0 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -399,18 +399,29 @@ impl Solution { ### C ```c -int minCostClimbingStairs(int* cost, int costSize){ - //开辟dp数组,大小为costSize - int *dp = (int *)malloc(sizeof(int) * costSize); - //初始化dp[0] = cost[0], dp[1] = cost[1] - dp[0] = cost[0], dp[1] = cost[1]; +#include +int minCostClimbingStairs(int *cost, int costSize) { + int dp[costSize + 1]; + dp[0] = dp[1] = 0; + for (int i = 2; i <= costSize; i++) { + dp[i] = fmin(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]); + } + return dp[costSize]; +} +``` - int i; - for(i = 2; i < costSize; ++i) { - dp[i] = (dp[i-1] < dp[i-2] ? dp[i-1] : dp[i-2]) + cost[i]; - } - //选出倒数2层楼梯中较小的 - return dp[i-1] < dp[i-2] ? dp[i-1] : dp[i-2]; +不使用 dp 数组 + +```c +#include +int minCostClimbingStairs(int *cost, int costSize) { + int dpBefore = 0, dpAfter = 0; + for (int i = 2; i <= costSize; i++) { + int dpi = fmin(dpBefore + cost[i - 2], dpAfter + cost[i - 1]); + dpBefore = dpAfter; + dpAfter = dpi; + } + return dpAfter; } ``` From f7680ab01d27b57e97dfe85796ac7c3c28b06d41 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 17:01:45 +0800 Subject: [PATCH 29/92] =?UTF-8?q?Update=200062.=E4=B8=8D=E5=90=8C=E8=B7=AF?= =?UTF-8?q?=E5=BE=84.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0062.不同路径.md | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index bf436369..2ca15726 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -395,21 +395,14 @@ function uniquePaths(m: number, n: number): number { ```Rust impl Solution { pub fn unique_paths(m: i32, n: i32) -> i32 { - let m = m as usize; - let n = n as usize; - let mut dp = vec![vec![0; n]; m]; - for i in 0..m { - dp[i][0] = 1; + let (m, n) = (m as usize, n as usize); + let mut dp = vec![vec![1; n]; m]; + for i in 1..m { + for j in 1..n { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } - for j in 0..n { - dp[0][j] = 1; - } - for i in 1..m { - for j in 1..n { - dp[i][j] = dp[i-1][j] + dp[i][j-1]; - } - } - dp[m-1][n-1] + } + dp[m - 1][n - 1] } } ``` From 872402e5a4e2e227e889fd3103786c503f864abd Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 18:05:44 +0800 Subject: [PATCH 30/92] =?UTF-8?q?Update=200063.=E4=B8=8D=E5=90=8C=E8=B7=AF?= =?UTF-8?q?=E5=BE=84II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0063.不同路径II.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 85130ab4..8ab90e6d 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -493,6 +493,34 @@ impl Solution { } ``` +空间优化: + +```rust +impl Solution { + pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { + let mut dp = vec![0; obstacle_grid[0].len()]; + for (i, &v) in obstacle_grid[0].iter().enumerate() { + if v == 0 { + dp[i] = 1; + } else { + break; + } + } + for rows in obstacle_grid.iter().skip(1) { + for j in 0..rows.len() { + if rows[j] == 1 { + dp[j] = 0; + continue; + } else if j != 0 { + dp[j] += dp[j - 1]; + } + } + } + dp.pop().unwrap() + } +} +``` + ### C ```c From ced650c7bb9d43447e8445fff31469455440057e Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 18:06:59 +0800 Subject: [PATCH 31/92] =?UTF-8?q?Update=20problems/0063.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E8=B7=AF=E5=BE=84II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0063.不同路径II.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 8ab90e6d..8ff8c33f 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -510,7 +510,6 @@ impl Solution { for j in 0..rows.len() { if rows[j] == 1 { dp[j] = 0; - continue; } else if j != 0 { dp[j] += dp[j - 1]; } From bd22ad9257b90dbeb2db60f5cdd6c591f6288e37 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 18:51:26 +0800 Subject: [PATCH 32/92] =?UTF-8?q?Update=200343.=E6=95=B4=E6=95=B0=E6=8B=86?= =?UTF-8?q?=E5=88=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0343.整数拆分.md | 44 ++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index c2fbbdde..4df6c41f 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -319,6 +319,29 @@ pub fn integer_break(n: i32) -> i32 { } ``` +贪心: + +```rust +impl Solution { + pub fn integer_break(mut n: i32) -> i32 { + match n { + 2 => 1, + 3 => 2, + 4 => 4, + 5.. => { + let mut res = 1; + while n > 4 { + res *= 3; + n -= 3; + } + res * n + } + _ => panic!("Error"), + } + } +} +``` + ### TypeScript ```typescript @@ -344,27 +367,6 @@ function integerBreak(n: number): number { }; ``` -### Rust - -```Rust -impl Solution { - fn max(a: i32, b: i32) -> i32{ - if a > b { a } else { b } - } - pub fn integer_break(n: i32) -> i32 { - let n = n as usize; - let mut dp = vec![0; n + 1]; - dp[2] = 1; - for i in 3..=n { - for j in 1..i - 1 { - dp[i] = Self::max(dp[i], Self::max(((i - j) * j) as i32, dp[i - j] * j as i32)); - } - } - dp[n] - } -} -``` - ### C ```c From 7111943ac00f9cea2c4899f0211b2d0fcadeef62 Mon Sep 17 00:00:00 2001 From: BanTanger <88583317+BanTanger@users.noreply.github.com> Date: Thu, 13 Apr 2023 22:18:21 +0800 Subject: [PATCH 33/92] =?UTF-8?q?Update=200347.=E5=89=8DK=E4=B8=AA?= =?UTF-8?q?=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 之前的 java 代码调用的 api 过于难记忆,不利于白板书写,于是将优先级队列存储数据结构从 map.setEntry 改为 int[] 数组,方便大家记忆理解书写 --- problems/0347.前K个高频元素.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 0d268d9b..6c8b51b1 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -188,7 +188,33 @@ class Solution { } } ``` - +简化版代码: +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + // 优先级队列,为了避免复杂 api 操作,pq 存储数组 + // lambda 表达式设置优先级队列从大到小存储 o1 - o2 为从大到小,o2 - o1 反之 + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]); + int[] res = new int[k]; // 答案数组为 k 个元素 + Map map = new HashMap<>(); // 记录元素出现次数 + for(int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); + for(var x : map.entrySet()) { // entrySet 获取 k-v Set 集合 + // 将 kv 转化成数组 + int[] tmp = new int[2]; + tmp[0] = x.getKey(); + tmp[1] = x.getValue(); + pq.offer(tmp); + if(pq.size() > k) { + pq.poll(); + } + } + for(int i = 0; i < k; i ++) { + res[i] = pq.poll()[0]; // 获取优先队列里的元素 + } + return res; + } +} +``` Python: ```python From 341b0aa672e9ca2d8a5b1cea2bc5ba307e795eda Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 17 Apr 2023 10:37:39 +0800 Subject: [PATCH 34/92] =?UTF-8?q?Update=20problems/0746.=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=9C=80=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index f11439c0..31e7bd48 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -318,7 +318,7 @@ func min(a, b int) int { var minCostClimbingStairs = function(cost) { const dp = [0, 0] for (let i = 2; i <= cost.length; ++i) { - dp[i] = Math.min(dp[i -1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) } return dp[cost.length] }; From 9aaf02cc20156d385853f0d3f8c9eebc983bc9d7 Mon Sep 17 00:00:00 2001 From: sharky <1821984081@qq.com> Date: Tue, 18 Apr 2023 15:15:28 +0800 Subject: [PATCH 35/92] =?UTF-8?q?1005=E3=80=81K=E6=AC=A1=E5=8F=96=E5=8F=8D?= =?UTF-8?q?=E5=90=8E=E6=9C=80=E5=A4=A7=E5=8C=96=E7=9A=84=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E5=92=8C=EF=BC=8C=E6=9A=B4=E5=8A=9B=E8=A7=A3=E6=B3=95=EF=BC=8C?= =?UTF-8?q?java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1005.K次取反后最大化的数组和.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index cdf42511..18b07b89 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -145,7 +145,23 @@ class Solution { } } ``` - +```java +//暴力解法 +class Solution { + public int largestSumAfterKNegations(int[] nums, int k) { + int count = 0; + //循环k次 + for( int i = 0; i < k; i++ ){ + Arrays.sort( nums ); + nums[0] = -nums[0];//把最小值换成其相反数 + } + for ( int num : nums ){ + count += num;//累加 + } + return count; + } +} +``` ### Python ```python class Solution: From b7ea55c93b68391ecd87c39c06e2811f0ed6b98f Mon Sep 17 00:00:00 2001 From: Winson Huang Date: Tue, 18 Apr 2023 21:07:54 +0800 Subject: [PATCH 36/92] =?UTF-8?q?Update=200454.=E5=9B=9B=E6=95=B0=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改 Java 语言版本代码,让 HashMap 相关操作更简洁 --- problems/0454.四数相加II.md | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 411b60e8..abfc7c23 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -102,21 +102,14 @@ class Solution { //统计两个数组中的元素之和,同时统计出现的次数,放入map for (int i : nums1) { for (int j : nums2) { - int tmp = map.getOrDefault(i + j, 0); - if (tmp == 0) { - map.put(i + j, 1); - } else { - map.replace(i + j, tmp + 1); - } + int sum = i + j; + map.put(sum, map.getOrDefault(sum, 0) + 1); } } //统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数 for (int i : nums3) { for (int j : nums4) { - int tmp = map.getOrDefault(0 - i - j, 0); - if (tmp != 0) { - res += tmp; - } + res += map.getOrDefault(0 - i - j, 0); } } return res; From 747563607292b4fc84452c4f45c2d0504531a171 Mon Sep 17 00:00:00 2001 From: Winson Huang Date: Tue, 18 Apr 2023 21:19:42 +0800 Subject: [PATCH 37/92] =?UTF-8?q?Update=200383.=E8=B5=8E=E9=87=91=E4=BF=A1?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 Java 语言版本的代码添加长度判断 --- problems/0383.赎金信.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index d9a184b6..a3f87d4a 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -117,6 +117,10 @@ Java: ```Java class Solution { public boolean canConstruct(String ransomNote, String magazine) { + // shortcut + if (ransomNote.length() > magazine.length()) { + return false; + } // 定义一个哈希映射数组 int[] record = new int[26]; From 3f2a816f3096c6ccccba41c81b3975ca80f6d081 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 18 Apr 2023 18:23:24 -0400 Subject: [PATCH 38/92] =?UTF-8?q?Update=200112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java 統一迭代法 --- problems/0112.路径总和.md | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5958de93..b1457887 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -385,6 +385,42 @@ class solution { } } ``` +```Java 統一迭代法 + public boolean hasPathSum(TreeNode root, int targetSum) { + Stack treeNodeStack = new Stack<>(); + Stack sumStack = new Stack<>(); + + if(root == null) + return false; + treeNodeStack.add(root); + sumStack.add(root.val); + + while(!treeNodeStack.isEmpty()){ + TreeNode curr = treeNodeStack.peek(); + int tempsum = sumStack.pop(); + if(curr != null){ + treeNodeStack.pop(); + treeNodeStack.add(curr); + treeNodeStack.add(null); + sumStack.add(tempsum); + if(curr.right != null){ + treeNodeStack.add(curr.right); + sumStack.add(tempsum + curr.right.val); + } + if(curr.left != null){ + treeNodeStack.add(curr.left); + sumStack.add(tempsum + curr.left.val); + } + }else{ + treeNodeStack.pop(); + TreeNode temp = treeNodeStack.pop(); + if(temp.left == null && temp.right == null && tempsum == targetSum) + return true; + } + } + return false; + } +``` ### 0113.路径总和-ii From 0cfe55180439c77995abefaa02c5b61108203f3a Mon Sep 17 00:00:00 2001 From: asxy <17375702582@163.com> Date: Thu, 20 Apr 2023 11:14:43 +0800 Subject: [PATCH 39/92] =?UTF-8?q?Update=200647.=E5=9B=9E=E6=96=87=E5=AD=90?= =?UTF-8?q?=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 回文子串添加java动态规划简单版本的代码 --- problems/0647.回文子串.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 90e6da9f..521c8c26 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -267,6 +267,27 @@ class Solution { return ans; } } + +``` + +动态规划:简洁版 +```java +class Solution { + public int countSubstrings(String s) { + boolean[][] dp = new boolean[s.length()][s.length()]; + + int res = 0; + for (int i = s.length() - 1; i >= 0; i--) { + for (int j = i; j < s.length(); j++) { + if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || dp[i + 1][j - 1])) { + res++; + dp[i][j] = true; + } + } + } + return res; + } +} ``` 中心扩散法: From fca305039005936bc9678c01d7573d6a2f8552ba Mon Sep 17 00:00:00 2001 From: asxy Date: Thu, 20 Apr 2023 11:47:39 +0800 Subject: [PATCH 40/92] =?UTF-8?q?Update=200084.=E6=9F=B1=E7=8A=B6=E5=9B=BE?= =?UTF-8?q?=E4=B8=AD=E6=9C=80=E5=A4=A7=E7=9A=84=E7=9F=A9=E5=BD=A2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加单调栈精简java代码 --- problems/0084.柱状图中最大的矩形.md | 27 ++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index eb064143..f9a83508 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -307,6 +307,33 @@ class Solution { } } ``` +单调栈精简 +```java +class Solution { + public int largestRectangleArea(int[] heights) { + int[] newHeight = new int[heights.length + 2]; + System.arraycopy(heights, 0, newHeight, 1, heights.length); + newHeight[heights.length+1] = 0; + newHeight[0] = 0; + + Stack stack = new Stack<>(); + stack.push(0); + + int res = 0; + for (int i = 1; i < newHeight.length; i++) { + while (newHeight[i] < newHeight[stack.peek()]) { + int mid = stack.pop(); + int w = i - stack.peek() - 1; + int h = newHeight[mid]; + res = Math.max(res, w * h); + } + stack.push(i); + + } + return res; + } +} +``` Python3: From ad2acdb14ac6d633a0ad6e3b8f92d3e1f6c32881 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Thu, 20 Apr 2023 23:44:00 -0400 Subject: [PATCH 41/92] =?UTF-8?q?Update=200112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit add java iteration method for leetcode 113 (DFS统一迭代法) --- problems/0112.路径总和.md | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5958de93..d8ea0a18 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -446,6 +446,52 @@ class Solution { } } ``` +```java +// 解法3 DFS统一迭代法 +class Solution { + public List> pathSum(TreeNode root, int targetSum) { + List> result = new ArrayList<>(); + Stack nodeStack = new Stack<>(); + Stack sumStack = new Stack<>(); + Stack> pathStack = new Stack<>(); + if(root == null) + return result; + nodeStack.add(root); + sumStack.add(root.val); + pathStack.add(new ArrayList<>()); + + while(!nodeStack.isEmpty()){ + TreeNode currNode = nodeStack.peek(); + int currSum = sumStack.pop(); + ArrayList currPath = pathStack.pop(); + if(currNode != null){ + nodeStack.pop(); + nodeStack.add(currNode); + nodeStack.add(null); + sumStack.add(currSum); + currPath.add(currNode.val); + pathStack.add(new ArrayList(currPath)); + if(currNode.right != null){ + nodeStack.add(currNode.right); + sumStack.add(currSum + currNode.right.val); + pathStack.add(new ArrayList(currPath)); + } + if(currNode.left != null){ + nodeStack.add(currNode.left); + sumStack.add(currSum + currNode.left.val); + pathStack.add(new ArrayList(currPath)); + } + }else{ + nodeStack.pop(); + TreeNode temp = nodeStack.pop(); + if(temp.left == null && temp.right == null && currSum == targetSum) + result.add(new ArrayList(currPath)); + } + } + return result; + } +} +``` ## python From 7a41318056f7aa10ef7d4653dd1c3fb988b64448 Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Fri, 21 Apr 2023 22:27:05 +0800 Subject: [PATCH 42/92] Update --- problems/0047.全排列II.md | 13 +++++++++++++ problems/0055.跳跃游戏.md | 2 +- problems/0056.合并区间.md | 1 - problems/0112.路径总和.md | 2 +- problems/0455.分发饼干.md | 2 +- 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index b4f7a4d8..b1908fb4 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -158,6 +158,19 @@ if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) { 所以我通过举[1,1,1]的例子,把这两个去重的逻辑分别抽象成树形结构,大家可以一目了然:为什么两种写法都可以以及哪一种效率更高! +这里可能大家又有疑惑,既然 `used[i - 1] == false`也行而`used[i - 1] == true`也行,那为什么还要写这个条件呢? + +直接这样写 不就完事了? + +```cpp +if (i > 0 && nums[i] == nums[i - 1]) { + continue; +} +``` + +其实并不行,一定要加上 `used[i - 1] == false`或者`used[i - 1] == true`,因为 used[i - 1] 要一直是 true 或者一直是false 才可以,而不是 一会是true 一会又是false。 所以这个条件要写上。 + + 是不是豁然开朗了!! ## 其他语言版本 diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index a898263d..fa76bc27 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -46,8 +46,8 @@ 如图: +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230203105634.png) -![55.跳跃游戏](https://code-thinking-1253855093.file.myqcloud.com/pics/20201124154758229-20230310135019977.png) i每次移动只能在cover的范围内移动,每移动一个元素,cover得到该元素数值(新的覆盖范围)的补充,让i继续移动下去。 diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index d467ab1a..08a3cb31 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -106,7 +106,6 @@ class Solution { } } -} ``` ```java // 版本2 diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index e412d38e..43a623b5 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -17,7 +17,7 @@ 示例: 给定如下二叉树,以及目标和 sum = 22, -![112.路径总和1](https://img-blog.csdnimg.cn/20210203160355234.png) +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230407210247.png) 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。 diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 63525b03..e525175b 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -44,7 +44,7 @@ 如图: -![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230203105634.png) +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230405225628.png) 这个例子可以看出饼干9只有喂给胃口为7的小孩,这样才是整体最优解,并想不出反例,那么就可以撸代码了。 From 252e330a6b20fa13e81e4412c91f40547e0ba1b1 Mon Sep 17 00:00:00 2001 From: HOUSHENGREN <48871516+HOUSHENGREN@users.noreply.github.com> Date: Sun, 23 Apr 2023 14:36:27 +0800 Subject: [PATCH 43/92] =?UTF-8?q?Update=20=E5=88=B7=E5=8A=9B=E6=89=A3?= =?UTF-8?q?=E7=94=A8=E4=B8=8D=E7=94=A8=E5=BA=93=E5=87=BD=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix:文字错误 --- problems/前序/刷力扣用不用库函数.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/前序/刷力扣用不用库函数.md b/problems/前序/刷力扣用不用库函数.md index ae0940bf..04fce856 100644 --- a/problems/前序/刷力扣用不用库函数.md +++ b/problems/前序/刷力扣用不用库函数.md @@ -24,5 +24,5 @@ 例如for循环里套一个字符串的insert,erase之类的操作,你说时间复杂度是多少呢,很明显是O(n^2)的时间复杂度了。 -在刷题的时候本着我说的标准来使用库函数,详细对大家回有所帮助! +在刷题的时候本着我说的标准来使用库函数,相信对大家回有所帮助! From b8f6df60c432fd85d9417e0ce138a90b4603527e Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Sun, 23 Apr 2023 02:40:34 -0400 Subject: [PATCH 44/92] =?UTF-8?q?Update=200106.=E4=BB=8E=E4=B8=AD=E5=BA=8F?= =?UTF-8?q?=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增一java寫法 和卡哥的思路一樣的 --- ...序与后序遍历序列构造二叉树.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index adb374f9..8fc973e0 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -622,7 +622,42 @@ class Solution { } } ``` +```java +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + if(postorder.length == 0 || inorder.length == 0) + return null; + return buildHelper(inorder, 0, inorder.length, postorder, 0, postorder.length); + + } + private TreeNode buildHelper(int[] inorder, int inorderStart, int inorderEnd, int[] postorder, int postorderStart, int postorderEnd){ + if(postorderStart == postorderEnd) + return null; + int rootVal = postorder[postorderEnd - 1]; + TreeNode root = new TreeNode(rootVal); + int middleIndex; + for (middleIndex = inorderStart; middleIndex < inorderEnd; middleIndex++){ + if(inorder[middleIndex] == rootVal) + break; + } + int leftInorderStart = inorderStart; + int leftInorderEnd = middleIndex; + int rightInorderStart = middleIndex + 1; + int rightInorderEnd = inorderEnd; + + + int leftPostorderStart = postorderStart; + int leftPostorderEnd = postorderStart + (middleIndex - inorderStart); + int rightPostorderStart = leftPostorderEnd; + int rightPostorderEnd = postorderEnd - 1; + root.left = buildHelper(inorder, leftInorderStart, leftInorderEnd, postorder, leftPostorderStart, leftPostorderEnd); + root.right = buildHelper(inorder, rightInorderStart, rightInorderEnd, postorder, rightPostorderStart, rightPostorderEnd); + + return root; + } +} +``` 105.从前序与中序遍历序列构造二叉树 ```java From 9558af957bd2077773a11fb4ebae7e432838c08a Mon Sep 17 00:00:00 2001 From: Charlie <1753524606@qq.com> Date: Sun, 23 Apr 2023 14:55:28 +0800 Subject: [PATCH 45/92] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200028.=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0strStr=20Rust=E7=89=88=E6=9C=AC=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 263c1689..2a81db88 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1314,7 +1314,6 @@ impl Solution { pub fn str_str(haystack: String, needle: String) -> i32 { let (haystack_len, needle_len) = (haystack.len(), needle.len()); - if haystack_len == 0 { return 0; } if haystack_len < needle_len { return -1;} let (haystack, needle) = (haystack.chars().collect::>(), needle.chars().collect::>()); let mut next: Vec = vec![0; haystack_len]; @@ -1355,9 +1354,6 @@ impl Solution { next } pub fn str_str(haystack: String, needle: String) -> i32 { - if needle.is_empty() { - return 0; - } if haystack.len() < needle.len() { return -1; } From f17c74ceec294a90f864a1a9a3836a03b4a752bb Mon Sep 17 00:00:00 2001 From: HOUSHENGREN <48871516+HOUSHENGREN@users.noreply.github.com> Date: Sun, 23 Apr 2023 15:14:25 +0800 Subject: [PATCH 46/92] =?UTF-8?q?Update=20=E5=88=B7=E5=8A=9B=E6=89=A3?= =?UTF-8?q?=E7=94=A8=E4=B8=8D=E7=94=A8=E5=BA=93=E5=87=BD=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat:修改文案 --- problems/前序/刷力扣用不用库函数.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/前序/刷力扣用不用库函数.md b/problems/前序/刷力扣用不用库函数.md index 04fce856..7d0e3475 100644 --- a/problems/前序/刷力扣用不用库函数.md +++ b/problems/前序/刷力扣用不用库函数.md @@ -24,5 +24,5 @@ 例如for循环里套一个字符串的insert,erase之类的操作,你说时间复杂度是多少呢,很明显是O(n^2)的时间复杂度了。 -在刷题的时候本着我说的标准来使用库函数,相信对大家回有所帮助! +在刷题的时候本着我说的标准来使用库函数,相信对大家会有所帮助! From ad871dae77cfed61609d3bffd14e2fd994ae7d1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=93=88=E5=93=88=E5=93=88?= <76643786+Projecthappy@users.noreply.github.com> Date: Sun, 23 Apr 2023 18:22:29 +0800 Subject: [PATCH 47/92] =?UTF-8?q?Update=200225.=E7=94=A8=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=A0=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为使用两个 Queue 实现添加新方法,方法将q1作为主要的队列,其元素排列顺序和出栈顺序相同,q2仅作为临时放置,push方法中在加入元素时先将q1中的元素依次出栈压入q2,然后将新加入的元素压入q1,再将q2中的元素依次出栈压入q1,其他方法可直接使用Queue中已有的方法。 --- problems/0225.用队列实现栈.md | 38 ++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index bad2faec..29ef0933 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -166,7 +166,7 @@ public: Java: -使用两个 Queue 实现 +使用两个 Queue 实现方法1 ```java class MyStack { @@ -208,6 +208,42 @@ class MyStack { } ``` +使用两个 Queue 实现方法2 +```java +class MyStack { + //q1作为主要的队列,其元素排列顺序和出栈顺序相同 + Queue q1 = new ArrayDeque<>(); + //q2仅作为临时放置 + Queue q2 = new ArrayDeque<>(); + + public MyStack() { + + } + //在加入元素时先将q1中的元素依次出栈压入q2,然后将新加入的元素压入q1,再将q2中的元素依次出栈压入q1 + public void push(int x) { + while (q1.size() > 0) { + q2.add(q1.poll()); + } + q1.add(x); + while (q2.size() > 0) { + q1.add(q2.poll()); + } + } + + public int pop() { + return q1.poll(); + } + + public int top() { + return q1.peek(); + } + + public boolean empty() { + return q1.isEmpty(); + } +} +``` + 使用两个 Deque 实现 ```java class MyStack { From dd290cf33ba44e857021985197122a2982d76874 Mon Sep 17 00:00:00 2001 From: Binbin Date: Mon, 24 Apr 2023 14:28:47 +0800 Subject: [PATCH 48/92] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=200104.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?.md=20=E9=87=8C=E7=9A=84=E9=94=99=E5=88=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后者 -> 或者 --- problems/0104.二叉树的最大深度.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 36578fd3..96169b32 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -38,7 +38,7 @@ 本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。 * 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始) -* 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始) +* 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始) **而根节点的高度就是二叉树的最大深度**,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。 From ce73cef055f17879a9ef8f58f8cabffd48ed7edb Mon Sep 17 00:00:00 2001 From: jimowo <1252480844@qq.com> Date: Mon, 24 Apr 2023 16:16:16 +0800 Subject: [PATCH 49/92] =?UTF-8?q?=E7=AE=97=E6=B3=95=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0198.打家劫舍.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index c25f3b86..6e7f5ab6 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -136,6 +136,29 @@ class Solution { return dp[nums.length - 1]; } } + +// 空间优化 dp数组只存与计算相关的两次数据 +class Solution { + public int rob(int[] nums) { + if (nums.length == 1) { + return nums[0]; + } + // 初始化dp数组 + // 优化空间 dp数组只用2格空间 只记录与当前计算相关的前两个结果 + int[] dp = new int[2]; + dp[0] = nums[0]; + dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; + int res = 0; + // 遍历 + for (int i = 2; i < nums.length; i++) { + res = (dp[0] + nums[i]) > dp[1] ? (dp[0] + nums[i]) : dp[1]; + dp[0] = dp[1]; + dp[1] = res; + } + // 输出结果 + return dp[1]; + } +} ``` Python: @@ -220,3 +243,4 @@ function rob(nums: number[]): number { + From bb8e7312b64b13f98ca6c6ae88260a4f57375acd Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 25 Apr 2023 03:25:45 -0400 Subject: [PATCH 50/92] =?UTF-8?q?Update=200098.=E9=AA=8C=E8=AF=81=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java 統一迭代法的寫法 有通過. AC --- problems/0098.验证二叉搜索树.md | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 95afe680..ccb63305 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -259,6 +259,36 @@ public: ## Java +```Java +//使用統一迭代法 +class Solution { + public boolean isValidBST(TreeNode root) { + Stack stack = new Stack<>(); + TreeNode pre = null; + if(root != null) + stack.add(root); + while(!stack.isEmpty()){ + TreeNode curr = stack.peek(); + if(curr != null){ + stack.pop(); + if(curr.right != null) + stack.add(curr.right); + stack.add(curr); + stack.add(null); + if(curr.left != null) + stack.add(curr.left); + }else{ + stack.pop(); + TreeNode temp = stack.pop(); + if(pre != null && pre.val >= temp.val) + return false; + pre = temp; + } + } + return true; + } +} +``` ```Java class Solution { // 递归 From 75c7f940d112893dd6a1f89f844b710a87b202e1 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 25 Apr 2023 04:03:17 -0400 Subject: [PATCH 51/92] =?UTF-8?q?=E6=96=B0=E5=A2=9Ejava=20=E7=B5=B1?= =?UTF-8?q?=E4=B8=80=E8=BF=AD=E4=BB=A3=E6=B3=95-=E4=B8=AD=E5=BA=8F?= =?UTF-8?q?=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java 統一迭代法-中序遍历 --- .../0530.二叉搜索树的最小绝对差.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index fa1430de..cd24c6fa 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -174,6 +174,39 @@ class Solution { } } ``` +統一迭代法-中序遍历 +```Java +class Solution { + public int getMinimumDifference(TreeNode root) { + Stack stack = new Stack<>(); + TreeNode pre = null; + int result = Integer.MAX_VALUE; + + if(root != null) + stack.add(root); + while(!stack.isEmpty()){ + TreeNode curr = stack.peek(); + if(curr != null){ + stack.pop(); + if(curr.right != null) + stack.add(curr.right); + stack.add(curr); + stack.add(null); + if(curr.left != null) + stack.add(curr.left); + }else{ + stack.pop(); + TreeNode temp = stack.pop(); + if(pre != null) + result = Math.min(result, temp.val - pre.val); + pre = temp; + } + } + return result; + } +} +``` + 迭代法-中序遍历 ```java From c5c7dfb7fe0c0e7aa5c2115bed085d417d0726c0 Mon Sep 17 00:00:00 2001 From: zbb Date: Tue, 25 Apr 2023 19:45:48 +0800 Subject: [PATCH 52/92] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=200101.=E5=AF=B9?= =?UTF-8?q?=E7=A7=B0=E4=BA=8C=E5=8F=89=E6=A0=91.md=20=E9=87=8C=E7=9A=84?= =?UTF-8?q?=E9=94=99=E5=88=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index b75e9ff2..1594196b 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -88,7 +88,7 @@ else if (left->val != right->val) return false; // 注意这里我没有 * 比较二叉树外侧是否对称:传入的是左节点的左孩子,右节点的右孩子。 -* 比较内测是否对称,传入左节点的右孩子,右节点的左孩子。 +* 比较内侧是否对称,传入左节点的右孩子,右节点的左孩子。 * 如果左右都对称就返回true ,有一侧不对称就返回false 。 代码如下: @@ -157,7 +157,7 @@ public: **这个代码就很简洁了,但隐藏了很多逻辑,条理不清晰,而且递归三部曲,在这里完全体现不出来。** -**所以建议大家做题的时候,一定要想清楚逻辑,每一步做什么。把道题目所有情况想到位,相应的代码写出来之后,再去追求简洁代码的效果。** +**所以建议大家做题的时候,一定要想清楚逻辑,每一步做什么。把题目所有情况想到位,相应的代码写出来之后,再去追求简洁代码的效果。** ## 迭代法 From 7851e51c7345590977d3881424354d6be0dd8eae Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 15:35:27 +0800 Subject: [PATCH 53/92] =?UTF-8?q?update=20=200077.=E7=BB=84=E5=90=88?= =?UTF-8?q?=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 9c6d481d..3f222a17 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -218,6 +218,10 @@ public: } }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n) + + 还记得我们在[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)中给出的回溯法模板么? From e533cb9cd4a5048a933055d5dd02ad7dbf8a1d20 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 15:37:21 +0800 Subject: [PATCH 54/92] =?UTF-8?q?update=20=20=200077.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E4=BC=98=E5=8C=96=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合优化.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 9736549c..0c816bc1 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -130,6 +130,10 @@ public: } }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n) + + # 总结 From 9a29e5c3be75185c6013aaa0cb252374fb80598d Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 15:41:40 +0800 Subject: [PATCH 55/92] =?UTF-8?q?update=20=20=200216.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8CIII=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0216.组合总和III.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index f631c3cd..f08d77ea 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -235,6 +235,8 @@ public: } }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n) # 总结 From 025854e1678ba1e77a271b35a60159c1ad92ffbb Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:02:29 +0800 Subject: [PATCH 56/92] =?UTF-8?q?update=20=20=200017.=E7=94=B5=E8=AF=9D?= =?UTF-8?q?=E5=8F=B7=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88?= =?UTF-8?q?=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index d1135497..d506bb88 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -183,6 +183,8 @@ public: } }; ``` +* 时间复杂度: O(3^m * 4^n),其中 m 是对应四个字母的数字个数,n 是对应三个字母的数字个数 +* 空间复杂度: O(3^m * 4^n) 一些写法,是把回溯的过程放在递归函数里了,例如如下代码,我可以写成这样:(注意注释中不一样的地方) From d3290c7e773f66514625e8d678ff7695ae3f0f99 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:07:21 +0800 Subject: [PATCH 57/92] =?UTF-8?q?update=20=20=200039.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8C=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index c4ee5ca6..e1e51923 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -214,6 +214,8 @@ public: } }; ``` +* 时间复杂度: O(n * 2^n),注意这只是复杂度的上界,因为剪枝的存在,真实的时间复杂度远小于此 +* 空间复杂度: O(target) # 总结 From d68a1f633e532621ebd87578ae7c8daae4e5c36c Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:08:26 +0800 Subject: [PATCH 58/92] =?UTF-8?q?update=20=20=200040.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8CII=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 83708df7..b708650a 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -214,6 +214,8 @@ public: }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n) ## 补充 From 65f059ac7a7168a8848bb7106f1050ce28afa862 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:27:02 +0800 Subject: [PATCH 59/92] =?UTF-8?q?update=20=200131.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E4=B8=B2=20=EF=BC=9A=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 30bba455..dfec7853 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -209,6 +209,9 @@ public: } }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n^2) + # 优化 上面的代码还存在一定的优化空间, 在于如何更高效的计算一个子字符串是否是回文字串。上述代码```isPalindrome```函数运用双指针的方法来判定对于一个字符串```s```, 给定起始下标和终止下标, 截取出的子字符串是否是回文字串。但是其中有一定的重复计算存在: From 33d5a6878e73800cae191d98276729c1ebb77860 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:33:52 +0800 Subject: [PATCH 60/92] =?UTF-8?q?=20update=20=20=200078.=E5=AD=90=E9=9B=86?= =?UTF-8?q?=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index f26d0821..07418fbc 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -149,6 +149,8 @@ public: }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n) 在注释中,可以发现可以不写终止条件,因为本来我们就要遍历整棵树。 From 3accc7602597a2d6c7af017326d8caf9cb30be16 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:34:55 +0800 Subject: [PATCH 61/92] =?UTF-8?q?update=20=20=200090.=E5=AD=90=E9=9B=86II?= =?UTF-8?q?=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 1a9f8fda..63f75d29 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -83,6 +83,9 @@ public: } }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n) + 使用set去重的版本。 ```CPP From 09975d3d380c3151538270fe8cac25d39a476281 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:37:53 +0800 Subject: [PATCH 62/92] =?UTF-8?q?update=20=20=200491.=E9=80=92=E5=A2=9E?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0491.递增子序列.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 436dbf01..d6c6b9c9 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -139,6 +139,8 @@ public: } }; ``` +* 时间复杂度: O(n * 2^n) +* 空间复杂度: O(n) ## 优化 From 9d581e86fe858577263597ec5b0a1aa5dda24c2e Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:38:59 +0800 Subject: [PATCH 63/92] =?UTF-8?q?update=20=200046.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97=20=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index e08aec94..fb70be41 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -136,6 +136,8 @@ public: } }; ``` +* 时间复杂度: O(n!) +* 空间复杂度: O(n) ## 总结 From 1a9cb629ae87aa43a7eac4dea0a6732492a8a242 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:39:37 +0800 Subject: [PATCH 64/92] =?UTF-8?q?update=20=200047.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97II=20=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0047.全排列II.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index b1908fb4..3ff3fb8f 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -99,6 +99,8 @@ public: }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(n) ## 拓展 From 2a7f4d5d4b4107c0aa85960e0e46adb56d665def Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 16:44:28 +0800 Subject: [PATCH 65/92] =?UTF-8?q?update=20=20=200051.N=E7=9A=87=E5=90=8E?= =?UTF-8?q?=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index bd1d1c9b..54580cf7 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -208,6 +208,9 @@ public: } }; ``` +* 时间复杂度: O(n!) +* 空间复杂度: O(n) + 可以看出,除了验证棋盘合法性的代码,省下来部分就是按照回溯法模板来的。 From 7f699b59167263645112138b8ff4a99e8c606846 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 27 Apr 2023 17:15:12 +0800 Subject: [PATCH 66/92] =?UTF-8?q?update=20=20=200093.=E5=A4=8D=E5=8E=9FIP?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 9d4d5918..161fb96e 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -244,6 +244,8 @@ public: }; ``` +* 时间复杂度: O(3^4),IP地址最多包含4个数字,每个数字最多有3种可能的分割方式,则搜索树的最大深度为4,每个节点最多有3个子节点。 +* 空间复杂度: O(n) # 总结 From 42cdaa2e9a2639dab6931a5733aabf6ed92df62a Mon Sep 17 00:00:00 2001 From: blockChain-Fans <33158355+1055373165@users.noreply.github.com> Date: Thu, 27 Apr 2023 23:34:50 +0800 Subject: [PATCH 67/92] =?UTF-8?q?Update=200035.=E6=90=9C=E7=B4=A2=E6=8F=92?= =?UTF-8?q?=E5=85=A5=E4=BD=8D=E7=BD=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 返回值应该是 right+1 把 --- problems/0035.搜索插入位置.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 58340c21..efc87577 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -274,7 +274,7 @@ func searchInsert(nums []int, target int) int { left = mid + 1 } } - return len(nums) + return right+1 } ``` From 31d2755d18a216384495f25654cd4510c360dadf Mon Sep 17 00:00:00 2001 From: xiaodi007 <334830452@qq.com> Date: Fri, 28 Apr 2023 11:17:08 +0800 Subject: [PATCH 68/92] fix 0343 py code --- problems/0343.整数拆分.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index c2fbbdde..812bf67b 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -254,7 +254,7 @@ class Solution: # 假设对正整数 i 拆分出的第一个正整数是 j(1 <= j < i),则有以下两种方案: # 1) 将 i 拆分成 j 和 i−j 的和,且 i−j 不再拆分成多个正整数,此时的乘积是 j * (i-j) # 2) 将 i 拆分成 j 和 i−j 的和,且 i−j 继续拆分成多个正整数,此时的乘积是 j * dp[i-j] - for j in range(1, i / 2 + 1): + for j in range(1, i // 2 + 1): dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j])) return dp[n] ``` From 14c25f2eeff8e024f822485c4fbdfddcb0c3710e Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 28 Apr 2023 18:30:16 +0800 Subject: [PATCH 69/92] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-1.md=20about=20?= =?UTF-8?q?rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index c45fc3d3..c2525248 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -573,6 +573,39 @@ object Solution { } ``` +### Rust + +```rust +pub struct Solution; + +impl Solution { + pub fn wei_bag_problem1(weight: Vec, value: Vec, bag_size: usize) -> usize { + let mut dp = vec![vec![0; bag_size + 1]; weight.len()]; + for j in weight[0]..=weight.len() { + dp[0][j] = value[0]; + } + + for i in 1..weight.len() { + for j in 0..=bag_size { + match j < weight[i] { + true => dp[i][j] = dp[i - 1][j], + false => dp[i][j] = dp[i - 1][j].max(dp[i - 1][j - weight[i]] + value[i]), + } + } + } + dp[weight.len() - 1][bag_size] + } +} + +#[test] +fn test_wei_bag_problem1() { + println!( + "{}", + Solution::wei_bag_problem1(vec![1, 3, 4], vec![15, 20, 30], 4) + ); +} +``` +

From e6ad637e6475c73766f401b052a1c523d171d059 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 28 Apr 2023 18:50:56 +0800 Subject: [PATCH 70/92] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-2.md=20about=20?= =?UTF-8?q?rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-2.md | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index baa4107f..1ce90440 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -406,6 +406,34 @@ object Solution { } ``` +### Rust + +```rust +pub struct Solution; + +impl Solution { + pub fn wei_bag_problem2(weight: Vec, value: Vec, bag_size: usize) -> usize { + let mut dp = vec![0; bag_size + 1]; + for i in 0..weight.len() { + for j in (weight[i]..=bag_size).rev() { + if j >= weight[i] { + dp[j] = dp[j].max(dp[j - weight[i]] + value[i]); + } + } + } + dp[dp.len() - 1] + } +} + +#[test] +fn test_wei_bag_problem2() { + println!( + "{}", + Solution::wei_bag_problem1(vec![1, 3, 4], vec![15, 20, 30], 4) + ); +} +``` +

From d2650cc436980c2553003e3c7bdba2e8579aa53b Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 28 Apr 2023 18:51:38 +0800 Subject: [PATCH 71/92] =?UTF-8?q?Update=20problems/=E8=83=8C=E5=8C=85?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index 1ce90440..3b798334 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -429,7 +429,7 @@ impl Solution { fn test_wei_bag_problem2() { println!( "{}", - Solution::wei_bag_problem1(vec![1, 3, 4], vec![15, 20, 30], 4) + Solution::wei_bag_problem2(vec![1, 3, 4], vec![15, 20, 30], 4) ); } ``` From 3ff604055147700bd66ad8c83b43ee6f073e4265 Mon Sep 17 00:00:00 2001 From: lzxzz <1042183935@qq.com> Date: Sat, 29 Apr 2023 09:49:25 +0800 Subject: [PATCH 72/92] optimize --- ....删除字符串中的所有相邻重复项.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 694f1a92..486d198b 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -264,14 +264,15 @@ javaScript: ```js var removeDuplicates = function(s) { - const stack = []; - for(const x of s) { - let c = null; - if(stack.length && x === (c = stack.pop())) continue; - c && stack.push(c); - stack.push(x); + const result = [] + for(const i of s){ + if(i === result[result.length-1]){ + result.pop() + }else{ + result.push(i) + } } - return stack.join(""); + return result.join('') }; ``` From 76d347076b1ff05769c6bbb8844027363608e017 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Sat, 29 Apr 2023 10:27:48 +0800 Subject: [PATCH 73/92] =?UTF-8?q?Update=200416.=E5=88=86=E5=89=B2=E7=AD=89?= =?UTF-8?q?=E5=92=8C=E5=AD=90=E9=9B=86.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 去除不必要的方法 --- problems/0416.分割等和子集.md | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 8726bf95..8115e18e 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -406,24 +406,21 @@ var canPartition = function(nums) { ```Rust impl Solution { - fn max(a: usize, b: usize) -> usize { - if a > b { a } else { b } - } pub fn can_partition(nums: Vec) -> bool { - let nums = nums.iter().map(|x| *x as usize).collect::>(); - let mut sum = 0; - let mut dp: Vec = vec![0; 10001]; - for i in 0..nums.len() { - sum += nums[i]; + let sum = nums.iter().sum::() as usize; + if sum % 2 == 1 { + return false; } - if sum % 2 == 1 { return false; } let target = sum / 2; - for i in 0..nums.len() { - for j in (nums[i]..=target).rev() { - dp[j] = Self::max(dp[j], dp[j - nums[i]] + nums[i]); + let mut dp = vec![0; target + 1]; + for n in nums { + for j in (n as usize..=target).rev() { + dp[j] = dp[j].max(dp[j - n as usize] + n) } } - if dp[target] == target { return true; } + if dp[target] == target as i32 { + return true; + } false } } From da4116bcb60b3bf6efa7f44e8e20877e987fadfe Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Sat, 29 Apr 2023 05:45:01 -0400 Subject: [PATCH 74/92] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20Java=20=E7=B5=B1?= =?UTF-8?q?=E4=B8=80=E8=BF=AD=E4=BB=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 Java 統一迭代法 --- problems/0501.二叉搜索树中的众数.md | 53 ++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index b7ef606f..e467bf8a 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -472,6 +472,59 @@ class Solution { } } ``` +統一迭代法 +```Java +class Solution { + public int[] findMode(TreeNode root) { + int count = 0; + int maxCount = 0; + TreeNode pre = null; + LinkedList res = new LinkedList<>(); + Stack stack = new Stack<>(); + + if(root != null) + stack.add(root); + + while(!stack.isEmpty()){ + TreeNode curr = stack.peek(); + if(curr != null){ + stack.pop(); + if(curr.right != null) + stack.add(curr.right); + stack.add(curr); + stack.add(null); + if(curr.left != null) + stack.add(curr.left); + }else{ + stack.pop(); + TreeNode temp = stack.pop(); + if(pre == null) + count = 1; + else if(pre != null && pre.val == temp.val) + count++; + else + count = 1; + pre = temp; + if(count == maxCount) + res.add(temp.val); + if(count > maxCount){ + maxCount = count; + res.clear(); + res.add(temp.val); + } + } + } + int[] result = new int[res.size()]; + int i = 0; + for (int x : res){ + result[i] = x; + i++; + } + return result; + } +} +``` + ## Python From 513707ca713b2b199f8202e953b1a8dd2c40d447 Mon Sep 17 00:00:00 2001 From: skyclouds2001 <95597335+skyclouds2001@users.noreply.github.com> Date: Sun, 30 Apr 2023 14:24:26 +0800 Subject: [PATCH 75/92] =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E7=BB=93=E6=9E=84=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 30f5c467..9e0c29f5 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -101,8 +101,8 @@ public: ## 其他语言版本 +Java: -### Java ```Java public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { @@ -150,9 +150,9 @@ public class Solution { } ``` -### Python -```python +Python: +```python class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lenA, lenB = 0, 0 @@ -179,7 +179,7 @@ class Solution: return None ``` -### Go +Go: ```go func getIntersectionNode(headA, headB *ListNode) *ListNode { @@ -240,7 +240,7 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode { } ``` -### javaScript +JavaScript: ```js var getListLen = function(head) { @@ -352,6 +352,7 @@ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ``` Scala: + ```scala object Solution { def getIntersectionNode(headA: ListNode, headB: ListNode): ListNode = { From 113d1192a92b50ad8154b4b7717cdb5d9186d7a0 Mon Sep 17 00:00:00 2001 From: Mrzhugq <84071063+Mrzhugq@users.noreply.github.com> Date: Sun, 30 Apr 2023 16:45:31 +0800 Subject: [PATCH 76/92] =?UTF-8?q?Update=200035.=E6=90=9C=E7=B4=A2=E6=8F=92?= =?UTF-8?q?=E5=85=A5=E4=BD=8D=E7=BD=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 195行把空间复杂度写成时间复杂度了 --- problems/0035.搜索插入位置.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 58340c21..a37d67f5 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -191,8 +191,8 @@ public: }; ``` -* 时间复杂度:$O(\log n)$ -* 时间复杂度:$O(1)$ +* 时间复杂度:O(log n) +* 空间复杂度:O(1) ## 总结 From 18a16f9faffb7b796d174fb150e3dd601f6f82f4 Mon Sep 17 00:00:00 2001 From: Jia Tan Date: Sun, 30 Apr 2023 20:24:32 +0000 Subject: [PATCH 77/92] Ignore .DS_Store files. --- .DS_Store | Bin 6148 -> 0 bytes .gitignore | 1 + 2 files changed, 1 insertion(+) delete mode 100644 .DS_Store create mode 100644 .gitignore diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index da03c1c1b207c3ee04079084ecb15dcfff97ef95..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%}T>S5T317Q;OJwLXQhx3-<3)^bl)(0V4`psf{T$m}X1UTBHSVD*@yHz(SRn%3w1`N_?k*PTX z=s*u5cO3N-(d77z49It9K_3Pnz=e13&kcl&V-IdW@S|a|_{35R>BXgGloVwt;#QN%@Vis8VsHj`Xe9O(bW6^; z=;?2>^71?{rY9N=vv=!y_4uZF|F|A+0!!OY6cR47cXj`MRB4$Rg_Eiph0d}LrjcXRUo z-}}7&|CmHQVt^R Date: Sun, 30 Apr 2023 13:40:16 -0700 Subject: [PATCH 78/92] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index 3afedc82..dbf42ca4 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -195,15 +195,16 @@ Java: ```java public class TreeNode { int val; - TreeNode left; - TreeNode right; - TreeNode() {} - TreeNode(int val) { this.val = val; } - TreeNode(int val, TreeNode left, TreeNode right) { - this.val = val; - this.left = left; - this.right = right; - } + TreeNode left; + TreeNode right; + + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } } ``` @@ -212,10 +213,10 @@ Python: ```python class TreeNode: - def __init__(self, value): - self.value = value - self.left = None - self.right = None + def __init__(self, val, left = None, right = None): + self.val = val + self.left = left + self.right = right ``` Go: From d6b1f3e9538c67b5592a0d93aee4df70a652ab96 Mon Sep 17 00:00:00 2001 From: JaneyLin <105125897+janeyziqinglin@users.noreply.github.com> Date: Tue, 2 May 2023 23:28:44 -0400 Subject: [PATCH 79/92] =?UTF-8?q?Update=200674.=E6=9C=80=E9=95=BF=E8=BF=9E?= =?UTF-8?q?=E7=BB=AD=E9=80=92=E5=A2=9E=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix bug. --- problems/0674.最长连续递增序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index 79a8311d..1e79b797 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -212,7 +212,7 @@ class Solution: return 0 result = 1 dp = [1] * len(nums) - for i in range(len(nums)-1): + for i in range(len(nums)): if nums[i+1] > nums[i]: #连续记录 dp[i+1] = dp[i] + 1 result = max(result, dp[i+1]) From f80761a43833de34dc355d48f729c64ecef63afb Mon Sep 17 00:00:00 2001 From: JaneyLin <105125897+janeyziqinglin@users.noreply.github.com> Date: Tue, 2 May 2023 23:34:57 -0400 Subject: [PATCH 80/92] =?UTF-8?q?Update=200300.=E6=9C=80=E9=95=BF=E4=B8=8A?= =?UTF-8?q?=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit result should be initialized to 1. --- problems/0300.最长上升子序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index e8cb0b5f..01d34949 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -149,7 +149,7 @@ class Solution: if len(nums) <= 1: return len(nums) dp = [1] * len(nums) - result = 0 + result = 1 for i in range(1, len(nums)): for j in range(0, i): if nums[i] > nums[j]: From c76ed37fc487bc7da34403bbb484e9e42b582efb Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 2 May 2023 23:55:58 -0400 Subject: [PATCH 81/92] adding java iteration method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java 迭代方法 --- problems/0669.修剪二叉搜索树.md | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 18d8a0cc..5739f762 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -248,6 +248,8 @@ public: ## Java +**递归** + ```Java class Solution { public TreeNode trimBST(TreeNode root, int low, int high) { @@ -269,6 +271,46 @@ class Solution { ``` +**迭代** + +```Java +class Solution { + //iteration + public TreeNode trimBST(TreeNode root, int low, int high) { + if(root == null) + return null; + while(root != null && (root.val < low || root.val > high)){ + if(root.val < low) + root = root.right; + else + root = root.left; + } + + TreeNode curr = root; + + //deal with root's left sub-tree, and deal with the value smaller than low. + while(curr != null){ + while(curr.left != null && curr.left.val < low){ + curr.left = curr.left.right; + } + curr = curr.left; + } + //go back to root; + curr = root; + + //deal with root's righg sub-tree, and deal with the value bigger than high. + while(curr != null){ + while(curr.right != null && curr.right.val > high){ + curr.right = curr.right.left; + } + curr = curr.right; + } + return root; + } +} + +```` + ## Python **递归** From 926008cf1390c596c7225f0f988723fe687a9408 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Wed, 3 May 2023 18:08:11 -0400 Subject: [PATCH 82/92] adding java iteraion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java統一迭代法 --- ...38.把二叉搜索树转换为累加树.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index ad5310e1..e60d9a84 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -177,6 +177,8 @@ public: ## Java +**递归** + ```Java class Solution { int sum; @@ -198,6 +200,42 @@ class Solution { } } ``` +**迭代** + +```Java +class Solution { + //DFS iteraion統一迭代法 + public TreeNode convertBST(TreeNode root) { + int pre = 0; + Stack stack = new Stack<>(); + if(root == null) //edge case check + return null; + + stack.add(root); + + while(!stack.isEmpty()){ + TreeNode curr = stack.peek(); + //curr != null的狀況,只負責存node到stack中 + if(curr != null){ + stack.pop(); + if(curr.left != null) //左 + stack.add(curr.left); + stack.add(curr); //中 + stack.add(null); + if(curr.right != null) //右 + stack.add(curr.right); + }else{ + //curr == null的狀況,只負責做單層邏輯 + stack.pop(); + TreeNode temp = stack.pop(); + temp.val += pre; + pre = temp.val; + } + } + return root; + } +} +``` ## Python **递归** From ae3fc9f57688e6369f593e6dab8e8f1d55a8c919 Mon Sep 17 00:00:00 2001 From: JaneyLin <105125897+janeyziqinglin@users.noreply.github.com> Date: Wed, 3 May 2023 21:02:58 -0400 Subject: [PATCH 83/92] =?UTF-8?q?Update=200053.=E6=9C=80=E5=A4=A7=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=92=8C=EF=BC=88=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92?= =?UTF-8?q?=EF=BC=89.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 题目已定义1 <= nums.length. --- problems/0053.最大子序和(动态规划).md | 2 -- 1 file changed, 2 deletions(-) diff --git a/problems/0053.最大子序和(动态规划).md b/problems/0053.最大子序和(动态规划).md index c7d1b2fd..bd490912 100644 --- a/problems/0053.最大子序和(动态规划).md +++ b/problems/0053.最大子序和(动态规划).md @@ -139,8 +139,6 @@ Python: ```python class Solution: def maxSubArray(self, nums: List[int]) -> int: - if len(nums) == 0: - return 0 dp = [0] * len(nums) dp[0] = nums[0] result = dp[0] From b794dccc5b40c1fa25dc2413edd0bbfda9e20aac Mon Sep 17 00:00:00 2001 From: JaneyLin <105125897+janeyziqinglin@users.noreply.github.com> Date: Wed, 3 May 2023 21:05:55 -0400 Subject: [PATCH 84/92] =?UTF-8?q?Update=200674.=E6=9C=80=E9=95=BF=E8=BF=9E?= =?UTF-8?q?=E7=BB=AD=E9=80=92=E5=A2=9E=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0674.最长连续递增序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index 1e79b797..79a8311d 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -212,7 +212,7 @@ class Solution: return 0 result = 1 dp = [1] * len(nums) - for i in range(len(nums)): + for i in range(len(nums)-1): if nums[i+1] > nums[i]: #连续记录 dp[i+1] = dp[i] + 1 result = max(result, dp[i+1]) From efc06ad7fdebe84477904b05c2e97b0adce6bedc Mon Sep 17 00:00:00 2001 From: Logen <47022821+Logenleedev@users.noreply.github.com> Date: Fri, 5 May 2023 13:57:17 -0500 Subject: [PATCH 85/92] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=B0=E7=9A=84?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0503.下一个更大元素II.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index bf651209..3fd4b3b6 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -164,6 +164,7 @@ class Solution { Python: ```python +# 方法 1: class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: dp = [-1] * len(nums) @@ -174,6 +175,26 @@ class Solution: stack.pop() stack.append(i%len(nums)) return dp + +# 方法 2: +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + stack = [] + # 创建答案数组 + ans = [-1] * len(nums1) + for i in range(len(nums2)): + while len(stack) > 0 and nums2[i] > nums2[stack[-1]]: + # 判断 num1 是否有 nums2[stack[-1]]。如果没有这个判断会出现指针异常 + if nums2[stack[-1]] in nums1: + # 锁定 num1 检索的 index + index = nums1.index(nums2[stack[-1]]) + # 更新答案数组 + ans[index] = nums2[i] + # 弹出小元素 + # 这个代码一定要放在 if 外面。否则单调栈的逻辑就不成立了 + stack.pop() + stack.append(i) + return ans ``` Go: ```go From 61d479ec47df5d3a1743c4de97ba0e4175954959 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Mon, 8 May 2023 15:59:31 -0400 Subject: [PATCH 86/92] improving java solution by using stringBuilder 1. improving java solution by using stringBuilder 2. adding explanation in the code --- problems/0093.复原IP地址.md | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 9d4d5918..7b15aad9 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -314,6 +314,47 @@ class Solution { return true; } } +//方法一:但使用stringBuilder,故优化时间、空间复杂度,因为向字符串插入字符时无需复制整个字符串,从而减少了操作的时间复杂度,也不用开新空间存subString,从而减少了空间复杂度。 +class Solution { + List result = new ArrayList<>(); + public List restoreIpAddresses(String s) { + StringBuilder sb = new StringBuilder(s); + backTracking(sb, 0, 0); + return result; + } + private void backTracking(StringBuilder s, int startIndex, int dotCount){ + if(dotCount == 3){ + if(isValid(s, startIndex, s.length() - 1)){ + result.add(s.toString()); + } + return; + } + for(int i = startIndex; i < s.length(); i++){ + if(isValid(s, startIndex, i)){ + s.insert(i + 1, '.'); + backTracking(s, i + 2, dotCount + 1); + s.deleteCharAt(i + 1); + }else{ + break; + } + } + } + //[start, end] + private boolean isValid(StringBuilder s, int start, int end){ + if(start > end) + return false; + if(s.charAt(start) == '0' && start != end) + return false; + int num = 0; + for(int i = start; i <= end; i++){ + int digit = s.charAt(i) - '0'; + num = num * 10 + digit; + if(num > 255) + return false; + } + return true; + } +} //方法二:比上面的方法时间复杂度低,更好地剪枝,优化时间复杂度 class Solution { @@ -358,6 +399,7 @@ class Solution { } ``` + ## python python2: From 38503ddc59e4554ac2316ca9c6e486b48285df8a Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 12 May 2023 20:41:46 +0800 Subject: [PATCH 87/92] =?UTF-8?q?Update=201049.=E6=9C=80=E5=90=8E=E4=B8=80?= =?UTF-8?q?=E5=9D=97=E7=9F=B3=E5=A4=B4=E7=9A=84=E9=87=8D=E9=87=8FII.md=20a?= =?UTF-8?q?bout=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1049.最后一块石头的重量II.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index 210ce737..a8150b1f 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -379,8 +379,23 @@ object Solution { } ``` +### Rust - +```rust +impl Solution { + pub fn last_stone_weight_ii(stones: Vec) -> i32 { + let sum = stones.iter().sum::(); + let target = sum as usize / 2; + let mut dp = vec![0; target + 1]; + for s in stones { + for j in (s as usize..=target).rev() { + dp[j] = dp[j].max(dp[j - s as usize] + s); + } + } + sum - dp[target] * 2 + } +} +```

From db21086b42d3a7ff1d07dbe4bfbf3e94bd2301b8 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 12 May 2023 22:09:19 +0800 Subject: [PATCH 88/92] =?UTF-8?q?Update=200494.=E7=9B=AE=E6=A0=87=E5=92=8C?= =?UTF-8?q?.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0494.目标和.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index cc2bc8df..e9e33370 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -417,6 +417,32 @@ object Solution { } ``` +### Rust + +```rust +impl Solution { + pub fn find_target_sum_ways(nums: Vec, target: i32) -> i32 { + let sum = nums.iter().sum::(); + if target.abs() > sum { + return 0; + } + if (target + sum) % 2 == 1 { + return 0; + } + let size = (sum + target) as usize / 2; + let mut dp = vec![0; size + 1]; + dp[0] = 1; + for n in nums { + for s in (n as usize..=size).rev() { + // + dp[s] += dp[s - n as usize]; + } + } + dp[size] + } +} +``` +

From 03829cde0d626a5d77609b29d6a1581924e40800 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 12 May 2023 22:09:48 +0800 Subject: [PATCH 89/92] Apply suggestions from code review --- problems/0494.目标和.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index e9e33370..c9f88892 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -434,7 +434,6 @@ impl Solution { dp[0] = 1; for n in nums { for s in (n as usize..=size).rev() { - // dp[s] += dp[s - n as usize]; } } From 1ed8111a24113240dc7707bc0cc4e56c575482e3 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Mon, 15 May 2023 15:21:03 -0400 Subject: [PATCH 90/92] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20```Java=20=E4=BB=A5?= =?UTF-8?q?=E6=AD=A3=E5=B8=B8=E9=A1=AF=E7=A4=BA=E4=BF=9D=E7=95=99=E5=AD=97?= =?UTF-8?q?=E9=A1=8F=E8=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 ```Java 以正常顯示保留字顏色 --- problems/0225.用队列实现栈.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 41a1ede2..94c79404 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -367,7 +367,7 @@ class MyStack { ``` 优化,使用一个 Queue 实现,但用卡哥的逻辑实现 -``` +```Java class MyStack { Queue queue; From 4948ef48f46d516a475f8bf57ab559b5a71513af Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Wed, 17 May 2023 16:50:29 -0400 Subject: [PATCH 91/92] =?UTF-8?q?=E6=96=B0=E5=A2=9Ejava=E8=A7=A3=E6=B3=95?= =?UTF-8?q?=E4=B8=AD=20lambda=E4=BB=A5=E5=8F=8Alinkedlist.add=E7=9A=84?= =?UTF-8?q?=E8=A8=BB=E9=87=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java解法中 lambda以及linkedlist.add的註釋 --- problems/0406.根据身高重建队列.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0406.根据身高重建队列.md b/problems/0406.根据身高重建队列.md index 3f82d0bc..67aef3ec 100644 --- a/problems/0406.根据身高重建队列.md +++ b/problems/0406.根据身高重建队列.md @@ -191,14 +191,14 @@ class Solution { public int[][] reconstructQueue(int[][] people) { // 身高从大到小排(身高相同k小的站前面) Arrays.sort(people, (a, b) -> { - if (a[0] == b[0]) return a[1] - b[1]; - return b[0] - a[0]; + if (a[0] == b[0]) return a[1] - b[1]; // a - b 是升序排列,故在a[0] == b[0]的狀況下,會根據k值升序排列 + return b[0] - a[0]; //b - a 是降序排列,在a[0] != b[0],的狀況會根據h值降序排列 }); LinkedList que = new LinkedList<>(); for (int[] p : people) { - que.add(p[1],p); + que.add(p[1],p); //Linkedlist.add(index, value),會將value插入到指定index裡。 } return que.toArray(new int[people.length][]); From 16f4a48bd6b0539c60eed95c4f2c54a052685386 Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Sat, 20 May 2023 15:30:25 +0800 Subject: [PATCH 92/92] update --- problems/0053.最大子序和.md | 2 +- problems/0121.买卖股票的最佳时机.md | 17 +++++++----- .../0122.买卖股票的最佳时机II.md | 2 +- ...票的最佳时机II(动态规划).md | 23 +++++++++------- .../0123.买卖股票的最佳时机III.md | 27 +++++++++++-------- .../0188.买卖股票的最佳时机IV.md | 17 +++++++----- problems/0198.打家劫舍.md | 4 +++ problems/0213.打家劫舍II.md | 25 ++++++++++------- ...09.最佳买卖股票时机含冷冻期.md | 4 +++ problems/0337.打家劫舍III.md | 5 ++++ ...佳时机含手续费(动态规划).md | 5 ++++ ...1005.K次取反后最大化的数组和.md | 23 ---------------- problems/动态规划理论基础.md | 5 ++++ 13 files changed, 92 insertions(+), 67 deletions(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 48f8be29..39c58332 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -124,7 +124,7 @@ public: ## 动态规划 -当然本题还可以用动态规划来做,当前[「代码随想录」](https://img-blog.csdnimg.cn/20201124161234338.png)主要讲解贪心系列,后续到动态规划系列的时候会详细讲解本题的 dp 方法。 +当然本题还可以用动态规划来做,在代码随想录动态规划章节我会详细介绍,如果大家想在想看,可以直接跳转:[动态规划版本详解](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) 那么先给出我的 dp 代码如下,有时间的录友可以提前做一做: diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 5b398f3f..753cb106 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -14,16 +14,21 @@ 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。 -示例 1: -输入:[7,1,5,3,6,4] -输出:5 +* 示例 1: +* 输入:[7,1,5,3,6,4] +* 输出:5 解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 -示例 2: -输入:prices = [7,6,4,3,1] -输出:0 +* 示例 2: +* 输入:prices = [7,6,4,3,1] +* 输出:0 解释:在这种情况下, 没有交易完成, 所以最大利润为 0。 +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划之 LeetCode:121.买卖股票的最佳时机1](https://www.bilibili.com/video/BV1Xe4y1u77q),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 思路 diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index e631c5e2..0d8ad608 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -102,7 +102,7 @@ public: ### 动态规划 -动态规划将在下一个系列详细讲解,本题解先给出我的 C++代码(带详细注释),感兴趣的同学可以自己先学习一下。 +动态规划将在下一个系列详细讲解,本题解先给出我的 C++代码(带详细注释),想先学习的话,可以看本篇:[122.买卖股票的最佳时机II(动态规划)](https://programmercarl.com/0122.%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BAII%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) ```CPP class Solution { diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 2779083d..146c6a4c 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -15,25 +15,30 @@ 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 -示例 1: -输入: [7,1,5,3,6,4] -输出: 7 +* 示例 1: +* 输入: [7,1,5,3,6,4] +* 输出: 7 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4。随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 -示例 2: -输入: [1,2,3,4,5] -输出: 4 +* 示例 2: +* 输入: [1,2,3,4,5] +* 输出: 4 解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。 -示例 3: -输入: [7,6,4,3,1] -输出: 0 +* 示例 3: +* 输入: [7,6,4,3,1] +* 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 提示: * 1 <= prices.length <= 3 * 10 ^ 4 * 0 <= prices[i] <= 10 ^ 4 +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划,股票问题第二弹 | LeetCode:122.买卖股票的最佳时机II](https://www.bilibili.com/video/BV1D24y1Q7Ls),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 思路 本题我们在讲解贪心专题的时候就已经讲解过了[贪心算法:买卖股票的最佳时机II](https://programmercarl.com/0122.买卖股票的最佳时机II.html),只不过没有深入讲解动态规划的解法,那么这次我们再好好分析一下动规的解法。 diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 33157238..af6870d4 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -15,23 +15,23 @@ 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 -示例 1: -输入:prices = [3,3,5,0,0,3,1,4] -输出:6 +* 示例 1: +* 输入:prices = [3,3,5,0,0,3,1,4] +* 输出:6 解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3。 -示例 2: -输入:prices = [1,2,3,4,5] -输出:4 +* 示例 2: +* 输入:prices = [1,2,3,4,5] +* 输出:4 解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4。注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。 -示例 3: -输入:prices = [7,6,4,3,1] -输出:0 +* 示例 3: +* 输入:prices = [7,6,4,3,1] +* 输出:0 解释:在这个情况下, 没有交易完成, 所以最大利润为0。 -示例 4: -输入:prices = [1] +* 示例 4: +* 输入:prices = [1] 输出:0 提示: @@ -39,6 +39,11 @@ * 1 <= prices.length <= 10^5 * 0 <= prices[i] <= 10^5 +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划,股票至多买卖两次,怎么求? | LeetCode:123.买卖股票最佳时机III](https://www.bilibili.com/video/BV1WG411K7AR),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 思路 diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index f6744a2b..37270664 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -14,14 +14,14 @@ 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 -示例 1: -输入:k = 2, prices = [2,4,1] -输出:2 +* 示例 1: +* 输入:k = 2, prices = [2,4,1] +* 输出:2 解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2。 -示例 2: -输入:k = 2, prices = [3,2,6,5,0,3] -输出:7 +* 示例 2: +* 输入:k = 2, prices = [3,2,6,5,0,3] +* 输出:7 解释:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4。随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。 @@ -31,6 +31,11 @@ * 0 <= prices.length <= 1000 * 0 <= prices[i] <= 1000 +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划来决定最佳时机,至多可以买卖K次!| LeetCode:188.买卖股票最佳时机4](https://www.bilibili.com/video/BV16M411U7XJ),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 思路 这道题目可以说是[动态规划:123.买卖股票的最佳时机III](https://programmercarl.com/0123.买卖股票的最佳时机III.html)的进阶版,这里要求至多有k次交易。 diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index c25f3b86..b7cdc1ce 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -31,6 +31,10 @@ * 0 <= nums.length <= 100 * 0 <= nums[i] <= 400 +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划,偷不偷这个房间呢?| LeetCode:198.打家劫舍](https://www.bilibili.com/video/BV1Te411N7SX),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + ## 思路 diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index becad069..aebda7f5 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -14,23 +14,28 @@ 示例 1: -输入:nums = [2,3,2] -输出:3 -解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。 +* 输入:nums = [2,3,2] +* 输出:3 +* 解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。 -示例 2: -输入:nums = [1,2,3,1] -输出:4 -解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。偷窃到的最高金额 = 1 + 3 = 4 。 +* 示例 2: +* 输入:nums = [1,2,3,1] +* 输出:4 +* 解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。偷窃到的最高金额 = 1 + 3 = 4 。 -示例 3: -输入:nums = [0] -输出:0 +* 示例 3: +* 输入:nums = [0] +* 输出:0 提示: * 1 <= nums.length <= 100 * 0 <= nums[i] <= 1000 +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划,房间连成环了那还偷不偷呢?| LeetCode:213.打家劫舍II](https://www.bilibili.com/video/BV1oM411B7xq),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 思路 这道题目和[198.打家劫舍](https://programmercarl.com/0198.打家劫舍.html)是差不多的,唯一区别就是成环了。 diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index d62e91c7..a56d9b84 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -20,6 +20,10 @@ * 输出: 3 * 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出] +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划来决定最佳时机,这次有冷冻期!| LeetCode:309.买卖股票的最佳时机含冷冻期](https://www.bilibili.com/video/BV1rP4y1D7ku),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + ## 思路 diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index f75c4c88..ca8cea23 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -16,6 +16,11 @@ ![337.打家劫舍III](https://code-thinking-1253855093.file.myqcloud.com/pics/20210223173849619.png) +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划,房间连成树了,偷不偷呢?| LeetCode:337.打家劫舍3](https://www.bilibili.com/video/BV1H24y1Q7sY),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 思路 这道题目和 [198.打家劫舍](https://programmercarl.com/0198.打家劫舍.html),[213.打家劫舍II](https://programmercarl.com/0213.打家劫舍II.html)也是如出一辙,只不过这个换成了树。 diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index 39730807..12789934 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -32,6 +32,11 @@ * 0 < prices[i] < 50000. * 0 <= fee < 50000. +# 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划来决定最佳时机,这次含手续费!| LeetCode:714.买卖股票的最佳时机含手续费](https://www.bilibili.com/video/BV1z44y1Z7UR),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 思路 本题贪心解法:[贪心算法:买卖股票的最佳时机含手续费](https://programmercarl.com/0714.买卖股票的最佳时机含手续费.html) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 27a575c7..6252c697 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -130,29 +130,6 @@ class Solution { } ``` -```java -class Solution { - public int largestSumAfterKNegations(int[] A, int K) { - if (A.length == 1) return k % 2 == 0 ? A[0] : -A[0]; - Arrays.sort(A); - int sum = 0; - int idx = 0; - for (int i = 0; i < K; i++) { - if (i < A.length - 1 && A[idx] < 0) { - A[idx] = -A[idx]; - if (A[idx] >= Math.abs(A[idx + 1])) idx++; - continue; - } - A[idx] = -A[idx]; - } - - for (int i = 0; i < A.length; i++) { - sum += A[i]; - } - return sum; - } -} -``` ### Python ```python diff --git a/problems/动态规划理论基础.md b/problems/动态规划理论基础.md index 77f01b13..a99c0690 100644 --- a/problems/动态规划理论基础.md +++ b/problems/动态规划理论基础.md @@ -10,6 +10,11 @@ +## 算法公开课 + +**《代码随想录》算法视频公开课:[动态规划理论基础](https://www.bilibili.com/video/BV13Q4y197Wg),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + ## 什么是动态规划 动态规划,英文:Dynamic Programming,简称DP,如果某一问题有很多重叠子问题,使用动态规划是最有效的。