From 3d6baa3ae3648ef41e7a96bd49cb68c3d9d2df2d Mon Sep 17 00:00:00 2001 From: dcj_hp <294487055@qq.com> Date: Fri, 20 May 2022 00:14:16 +0800 Subject: [PATCH 01/22] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20java=20=E4=B8=80?= =?UTF-8?q?=E7=BB=B4dp=E6=95=B0=E7=BB=84=E8=A7=A3=E6=B3=95=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1143.最长公共子序列.md | 44 ++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index ecedf89b..b4b8e6db 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -129,6 +129,9 @@ public: Java: ```java +/* + 二维dp数组 +*/ class Solution { public int longestCommonSubsequence(String text1, String text2) { int[][] dp = new int[text1.length() + 1][text2.length() + 1]; // 先对dp数组做初始化操作 @@ -146,6 +149,47 @@ class Solution { return dp[text1.length()][text2.length()]; } } + + + +/** + 一维dp数组 +*/ +class Solution { + public int longestCommonSubsequence(String text1, String text2) { + int n1 = text1.length(); + int n2 = text2.length(); + + // 多从二维dp数组过程分析 + // 关键在于 如果记录 dp[i - 1][j - 1] + // 因为 dp[i - 1][j - 1] dp[j - 1] <=> dp[i][j - 1] + int [] dp = new int[n2 + 1]; + + for(int i = 1; i <= n1; i++){ + + // 这里pre相当于 dp[i - 1][j - 1] + int pre = dp[0]; + for(int j = 1; j <= n2; j++){ + + //用于给pre赋值 + int cur = dp[j]; + if(text1.charAt(i - 1) == text2.charAt(j - 1)){ + //这里pre相当于dp[i - 1][j - 1] 千万不能用dp[j - 1] !! + dp[j] = pre + 1; + } else{ + // dp[j] 相当于 dp[i - 1][j] + // dp[j - 1] 相当于 dp[i][j - 1] + dp[j] = Math.max(dp[j], dp[j - 1]); + } + + //更新dp[i - 1][j - 1], 为下次使用做准备 + pre = cur; + } + } + + return dp[n2]; + } +} ``` Python: From bc3d202797ee1a2c276efd2b0b86cc00bd0f744a Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 5 Jun 2022 10:54:31 +0800 Subject: [PATCH 02/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880205.=E5=90=8C?= =?UTF-8?q?=E6=9E=84=E5=AD=97=E7=AC=A6=E4=B8=B2.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0205.同构字符串.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0205.同构字符串.md b/problems/0205.同构字符串.md index d4b71c59..337dcc73 100644 --- a/problems/0205.同构字符串.md +++ b/problems/0205.同构字符串.md @@ -156,6 +156,28 @@ var isIsomorphic = function(s, t) { }; ``` +## TypeScript + +```typescript +function isIsomorphic(s: string, t: string): boolean { + const helperMap1: Map = new Map(); + const helperMap2: Map = new Map(); + for (let i = 0, length = s.length; i < length; i++) { + let temp1: string | undefined = helperMap1.get(s[i]); + let temp2: string | undefined = helperMap2.get(t[i]); + if (temp1 === undefined && temp2 === undefined) { + helperMap1.set(s[i], t[i]); + helperMap2.set(t[i], s[i]); + } else if (temp1 !== t[i] || temp2 !== s[i]) { + return false; + } + } + return true; +}; +``` + + + -----------------------
From ccfb805417aa1f55efd1b30be662db8a92b46893 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sun, 5 Jun 2022 13:50:27 +0800 Subject: [PATCH 03/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200078.=E5=AD=90?= =?UTF-8?q?=E9=9B=86.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index e1c52b5b..3fc396a2 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -373,6 +373,60 @@ func subsets(_ nums: [Int]) -> [[Int]] { } ``` +## Scala + +思路一: 使用本题解思路 + +```scala +object Solution { + import scala.collection.mutable + def subsets(nums: Array[Int]): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + + def backtracking(startIndex: Int): Unit = { + result.append(path.toList) // 存放结果 + if (startIndex >= nums.size) { + return + } + for (i <- startIndex until nums.size) { + path.append(nums(i)) // 添加元素 + backtracking(i + 1) + path.remove(path.size - 1) // 删除 + } + } + + backtracking(0) + result.toList + } +} +``` + +思路二: 将原问题转换为二叉树,针对每一个元素都有**选或不选**两种选择,直到遍历到最后,所有的叶子节点即为本题的答案: + +```scala +object Solution { + import scala.collection.mutable + def subsets(nums: Array[Int]): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + + def backtracking(path: mutable.ListBuffer[Int], startIndex: Int): Unit = { + if (startIndex == nums.length) { + result.append(path.toList) + return + } + path.append(nums(startIndex)) + backtracking(path, startIndex + 1) // 选择元素 + path.remove(path.size - 1) + backtracking(path, startIndex + 1) // 不选择元素 + } + + backtracking(mutable.ListBuffer[Int](), 0) + result.toList + } +} +``` + -----------------------
From b3530189489235f1212b89bd9dba0281154f366c Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sun, 5 Jun 2022 14:13:41 +0800 Subject: [PATCH 04/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200090.=E5=AD=90?= =?UTF-8?q?=E9=9B=86II.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 74ce000b..9047a809 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -434,6 +434,63 @@ func subsetsWithDup(_ nums: [Int]) -> [[Int]] { } ``` +### Scala + +不使用userd数组: + +```scala +object Solution { + import scala.collection.mutable + def subsetsWithDup(nums: Array[Int]): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + var num = nums.sorted // 排序 + + def backtracking(startIndex: Int): Unit = { + result.append(path.toList) + if (startIndex >= num.size){ + return + } + for (i <- startIndex until num.size) { + // 同一树层重复的元素不进入回溯 + if (!(i > startIndex && num(i) == num(i - 1))) { + path.append(num(i)) + backtracking(i + 1) + path.remove(path.size - 1) + } + } + } + + backtracking(0) + result.toList + } +} +``` + +使用Set去重: +```scala +object Solution { + import scala.collection.mutable + def subsetsWithDup(nums: Array[Int]): List[List[Int]] = { + var result = mutable.Set[List[Int]]() + var num = nums.sorted + def backtracking(path: mutable.ListBuffer[Int], startIndex: Int): Unit = { + if (startIndex == num.length) { + result.add(path.toList) + return + } + path.append(num(startIndex)) + backtracking(path, startIndex + 1) // 选择 + path.remove(path.size - 1) + backtracking(path, startIndex + 1) // 不选择 + } + + backtracking(mutable.ListBuffer[Int](), 0) + + result.toList + } +} +``` -----------------------
From 068cc095353ceb240c98a6c2b8598e98c445260b Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sun, 5 Jun 2022 14:46:21 +0800 Subject: [PATCH 05/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200491.=E9=80=92?= =?UTF-8?q?=E5=A2=9E=E5=AD=90=E5=BA=8F=E5=88=97.md=20Scala=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0491.递增子序列.md | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 3ea2382b..a04d433b 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -522,5 +522,39 @@ func findSubsequences(_ nums: [Int]) -> [[Int]] { ``` +## Scala + +```scala +object Solution { + import scala.collection.mutable + def findSubsequences(nums: Array[Int]): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + + def backtracking(startIndex: Int): Unit = { + // 集合元素大于1,添加到结果集 + if (path.size > 1) { + result.append(path.toList) + } + + var used = new Array[Boolean](201) + // 使用循环守卫,当前层没有用过的元素才有资格进入回溯 + for (i <- startIndex until nums.size if !used(nums(i) + 100)) { + // 如果path没元素或 当前循环的元素比path的最后一个元素大,则可以进入回溯 + if (path.size == 0 || (!path.isEmpty && nums(i) >= path(path.size - 1))) { + used(nums(i) + 100) = true + path.append(nums(i)) + backtracking(i + 1) + path.remove(path.size - 1) + } + } + } + + backtracking(0) + result.toList + } +} +``` + -----------------------
From 9f38af3e3a61562b17530302e8d14a6a02d1835f Mon Sep 17 00:00:00 2001 From: Hang <69448559+silaslll@users.noreply.github.com> Date: Sun, 5 Jun 2022 17:59:15 -0400 Subject: [PATCH 06/22] =?UTF-8?q?Update=200452.=E7=94=A8=E6=9C=80=E5=B0=91?= =?UTF-8?q?=E6=95=B0=E9=87=8F=E7=9A=84=E7=AE=AD=E5=BC=95=E7=88=86=E6=B0=94?= =?UTF-8?q?=E7=90=83.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新了java代码,增加了一个 leftmostRightBound variable 记录最小的右边界使得代码可读性增加 加入了comment 解释了Arrays.sort(points, (x, y) -> Integer.compare(x[0], y[0])); 中不用 x[0] - y[0] 而是用Integer.compare(x[0], y[0]) 的原因 加入了时空复杂度和说明 --- .../0452.用最少数量的箭引爆气球.md | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index d4bbe961..58422d4c 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -136,17 +136,28 @@ public: ### Java ```java +/** +时间复杂度 : O(NlogN) 排序需要 O(NlogN) 的复杂度 + +空间复杂度 : O(logN) java所使用的内置函数用的是快速排序需要 logN 的空间 +*/ class Solution { public int findMinArrowShots(int[][] points) { if (points.length == 0) return 0; - Arrays.sort(points, (o1, o2) -> Integer.compare(o1[0], o2[0])); - + //用x[0] - y[0] 会大于2147483647 造成整型溢出 + Arrays.sort(points, (x, y) -> Integer.compare(x[0], y[0])); + //count = 1 因为最少需要一个箭来射击第一个气球 int count = 1; - for (int i = 1; i < points.length; i++) { - if (points[i][0] > points[i - 1][1]) { + //重叠气球的最小右边界 + int leftmostRightBound = points[0][1]; + //如果下一个气球的左边界大于最小右边界 + if (points[i][0] > leftmostRightBound ) { + //增加一次射击 count++; + leftmostRightBound = points[i][1]; + //不然就更新最小右边界 } else { - points[i][1] = Math.min(points[i][1],points[i - 1][1]); + leftmostRightBound = Math.min(leftmostRightBound , points[i][1]); } } return count; From 6d804e2b244891ab3c1a12ac9b34d3eafd64654c Mon Sep 17 00:00:00 2001 From: Grant Yang Date: Sun, 5 Jun 2022 21:24:56 -0400 Subject: [PATCH 07/22] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20111.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=20=E7=9A=84=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF=E5=8F=8A?= =?UTF-8?q?=E6=94=B9=E8=BF=9B=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 1743243d..d9fd0b30 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2393,21 +2393,21 @@ JavaScript: var minDepth = function(root) { if (root === null) return 0; let queue = [root]; - let deepth = 0; + let depth = 0; while (queue.length) { let n = queue.length; - deepth++; + depth++; for (let i=0; i Date: Sun, 5 Jun 2022 22:31:41 -0400 Subject: [PATCH 08/22] =?UTF-8?q?Update=200056.=E5=90=88=E5=B9=B6=E5=8C=BA?= =?UTF-8?q?=E9=97=B4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0056.合并区间.md | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index e444a221..98848963 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -136,24 +136,38 @@ public: ### Java ```java + +/** +时间复杂度 : O(NlogN) 排序需要O(NlogN) +空间复杂度 : O(logN) java 的内置排序是快速排序 需要 O(logN)空间 + +*/ class Solution { public int[][] merge(int[][] intervals) { List res = new LinkedList<>(); - Arrays.sort(intervals, (o1, o2) -> Integer.compare(o1[0], o2[0])); - + //按照左边界排序 + Arrays.sort(intervals, (x, y) -> Integer.compare(x[0], y[0])); + //initial start 是最小左边界 int start = intervals[0][0]; + int rightmostRightBound = intervals[0][1]; for (int i = 1; i < intervals.length; i++) { - if (intervals[i][0] > intervals[i - 1][1]) { - res.add(new int[]{start, intervals[i - 1][1]}); + //如果左边界大于最大右边界 + if (intervals[i][0] > rightmostRightBound) { + //加入区间 并且更新start + res.add(new int[]{start, rightmostRightBound}); start = intervals[i][0]; + rightmostRightBound = intervals[i][1]; } else { - intervals[i][1] = Math.max(intervals[i][1], intervals[i - 1][1]); + //更新最大右边界 + rightmostRightBound = Math.max(rightmostRightBound, intervals[i][1]); } } - res.add(new int[]{start, intervals[intervals.length - 1][1]}); + res.add(new int[]{start, rightmostRightBound}); return res.toArray(new int[res.size()][]); } } + +} ``` ```java // 版本2 From 091204c926a044f0ec86200cbdd3cca6deeaf97e Mon Sep 17 00:00:00 2001 From: HanMengnan <1448189829@qq.com> Date: Tue, 7 Jun 2022 10:46:43 +0800 Subject: [PATCH 09/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880129.=E6=B1=82?= =?UTF-8?q?=E6=A0=B9=E8=8A=82=E7=82=B9=E5=88=B0=E5=8F=B6=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E4=B9=8B=E5=92=8C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0129.求根到叶子节点数字之和.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index b271ca7d..4191bb26 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -3,6 +3,9 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ + + # 129. 求根节点到叶节点数字之和 [力扣题目链接](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/) @@ -245,6 +248,29 @@ class Solution: ``` Go: +```go +func sumNumbers(root *TreeNode) int { + sum = 0 + travel(root, root.Val) + return sum +} + +func travel(root *TreeNode, tmpSum int) { + if root.Left == nil && root.Right == nil { + sum += tmpSum + } else { + if root.Left != nil { + travel(root.Left, tmpSum*10+root.Left.Val) + } + if root.Right != nil { + travel(root.Right, tmpSum*10+root.Right.Val) + } + } +} +``` + + + JavaScript: ```javascript var sumNumbers = function(root) { From 97fc88e533418bf9070bd9fb549a23a2499805b4 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Tue, 7 Jun 2022 16:59:55 +0800 Subject: [PATCH 10/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200046.=E5=85=A8?= =?UTF-8?q?=E6=8E=92=E5=88=97.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 836c3646..ec3adaa7 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -456,6 +456,36 @@ func permute(_ nums: [Int]) -> [[Int]] { } ``` +### Scala + +```scala +object Solution { + import scala.collection.mutable + def permute(nums: Array[Int]): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + + def backtracking(used: Array[Boolean]): Unit = { + if (path.size == nums.size) { + // 如果path的长度和nums相等,那么可以添加到结果集 + result.append(path.toList) + return + } + // 添加循环守卫,只有当当前数字没有用过的情况下才进入回溯 + for (i <- nums.indices if used(i) == false) { + used(i) = true + path.append(nums(i)) + backtracking(used) // 回溯 + path.remove(path.size - 1) + used(i) = false + } + } + + backtracking(new Array[Boolean](nums.size)) // 调用方法 + result.toList // 最终返回结果集的List形式 + } +} +``` -----------------------
From 8537401616f10ce85038bbd94aa951a20bb877d6 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Tue, 7 Jun 2022 17:24:41 +0800 Subject: [PATCH 11/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200047.=E5=85=A8?= =?UTF-8?q?=E6=8E=92=E5=88=97II.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0047.全排列II.md | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index cce25cd9..0a5debcc 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -422,5 +422,43 @@ int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumn } ``` +### Scala + +```scala +object Solution { + import scala.collection.mutable + def permuteUnique(nums: Array[Int]): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + var num = nums.sorted // 首先对数据进行排序 + + def backtracking(used: Array[Boolean]): Unit = { + if (path.size == num.size) { + // 如果path的size等于num了,那么可以添加到结果集 + result.append(path.toList) + return + } + // 循环守卫,当前元素没被使用过就进入循环体 + for (i <- num.indices if used(i) == false) { + // 当前索引为0,不存在和前一个数字相等可以进入回溯 + // 当前索引值和上一个索引不相等,可以回溯 + // 前一个索引对应的值没有被选,可以回溯 + // 因为Scala没有continue,只能将逻辑反过来写 + if (i == 0 || (i > 0 && num(i) != num(i - 1)) || used(i-1) == false) { + used(i) = true + path.append(num(i)) + backtracking(used) + path.remove(path.size - 1) + used(i) = false + } + } + } + + backtracking(new Array[Boolean](nums.length)) + result.toList + } +} +``` + -----------------------
From fa26fb332b43cbeec805944f4522472953232487 Mon Sep 17 00:00:00 2001 From: dcj_hp <294487055@qq.com> Date: Tue, 7 Jun 2022 17:38:37 +0800 Subject: [PATCH 12/22] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20java=20dp=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0132.分割回文串II.md | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0132.分割回文串II.md b/problems/0132.分割回文串II.md index 87d3e4b4..4cb95901 100644 --- a/problems/0132.分割回文串II.md +++ b/problems/0132.分割回文串II.md @@ -206,6 +206,55 @@ public: ## Java ```java +class Solution { + + public int minCut(String s) { + if(null == s || "".equals(s)){ + return 0; + } + int len = s.length(); + // 1. + // 记录子串[i..j]是否是回文串 + boolean[][] isPalindromic = new boolean[len][len]; + // 从下到上,从左到右 + for(int i = len - 1; i >= 0; i--){ + for(int j = i; j < len; j++){ + if(s.charAt(i) == s.charAt(j)){ + if(j - i <= 1){ + isPalindromic[i][j] = true; + } else{ + isPalindromic[i][j] = isPalindromic[i + 1][j - 1]; + } + } else{ + isPalindromic[i][j] = false; + } + } + } + + // 2. + // dp[i] 表示[0..i]的最小分割次数 + int[] dp = new int[len]; + for(int i = 0; i < len; i++){ + //初始考虑最坏的情况。 1个字符分割0次, len个字符分割 len - 1次 + dp[i] = i; + } + + for(int i = 1; i < len; i++){ + if(isPalindromic[0][i]){ + // s[0..i]是回文了,那 dp[i] = 0, 一次也不用分割 + dp[i] = 0; + continue; + } + for(int j = 0; j < i; j++){ + // 按文中的思路,不清楚就拿 "ababa" 为例,先写出 isPalindromic 数组,再进行求解 + if(isPalindromic[j + 1][i]){ + dp[i] = Math.min(dp[i], dp[j] + 1); + } + } + } + return dp[len - 1]; + } +} ``` ## Python @@ -240,6 +289,7 @@ class Solution: ## Go ```go + ``` ## JavaScript From 7b95f173683f4eae7fd68c313839a678b2e1b79d Mon Sep 17 00:00:00 2001 From: Chris Chen Date: Tue, 7 Jun 2022 13:21:32 +0100 Subject: [PATCH 13/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0(0001.=E4=B8=A4?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C.md=EF=BC=89=EF=BC=9ADart=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 6969c2e2..4ba92092 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -317,6 +317,20 @@ public class Solution { } ``` +Dart: +```dart +List twoSum(List nums, int target) { + var tmp = []; + for (var i = 0; i < nums.length; i++) { + var rest = target - nums[i]; + if(tmp.contains(rest)){ + return [tmp.indexOf(rest), i]; + } + tmp.add(nums[i]); + } + return [0 , 0]; +} +``` -----------------------
From 371564ba3b9a2b9641cafc05eb033f8d162aec81 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Tue, 7 Jun 2022 22:19:13 +0800 Subject: [PATCH 14/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200051.N=E7=9A=87?= =?UTF-8?q?=E5=90=8E.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 74 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index c03e48c2..f65ccaf5 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -455,7 +455,7 @@ var solveNQueens = function(n) { }; ``` -## TypeScript +### TypeScript ```typescript function solveNQueens(n: number): string[][] { @@ -683,5 +683,77 @@ char *** solveNQueens(int n, int* returnSize, int** returnColumnSizes){ } ``` +### Scala + +```scala +object Solution { + import scala.collection.mutable + def solveNQueens(n: Int): List[List[String]] = { + var result = mutable.ListBuffer[List[String]]() + + def judge(x: Int, y: Int, maze: Array[Array[Boolean]]): Boolean = { + // 正上方 + var xx = x + while (xx >= 0) { + if (maze(xx)(y)) return false + xx -= 1 + } + // 左边 + var yy = y + while (yy >= 0) { + if (maze(x)(yy)) return false + yy -= 1 + } + // 左上方 + xx = x + yy = y + while (xx >= 0 && yy >= 0) { + if (maze(xx)(yy)) return false + xx -= 1 + yy -= 1 + } + xx = x + yy = y + // 右上方 + while (xx >= 0 && yy < n) { + if (maze(xx)(yy)) return false + xx -= 1 + yy += 1 + } + true + } + + def backtracking(row: Int, maze: Array[Array[Boolean]]): Unit = { + if (row == n) { + // 将结果转换为题目所需要的形式 + var path = mutable.ListBuffer[String]() + for (x <- maze) { + var tmp = mutable.ListBuffer[String]() + for (y <- x) { + if (y == true) tmp.append("Q") + else tmp.append(".") + } + path.append(tmp.mkString) + } + result.append(path.toList) + return + } + + for (j <- 0 until n) { + // 判断这个位置是否可以放置皇后 + if (judge(row, j, maze)) { + maze(row)(j) = true + backtracking(row + 1, maze) + maze(row)(j) = false + } + } + } + + backtracking(0, Array.ofDim[Boolean](n, n)) + result.toList + } +} +``` + -----------------------
From ffe981fb6c5af5c7400f3b82c455b80ac8333fc0 Mon Sep 17 00:00:00 2001 From: AronJudge <2286381138@qq.com> Date: Sun, 26 Jun 2022 23:50:32 +0800 Subject: [PATCH 15/22] =?UTF-8?q?0977.=20=E6=9C=89=E5=BA=8F=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9=20=E6=B7=BB=E5=8A=A0Java?= =?UTF-8?q?=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 1 + 1 file changed, 1 insertion(+) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 20bdf7b0..d274d778 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -106,6 +106,7 @@ class Solution { int index = result.length - 1; while (left <= right) { if (nums[left] * nums[left] > nums[right] * nums[right]) { + // 正数的相对位置是不变的, 需要调整的是负数平方后的相对位置 result[index--] = nums[left] * nums[left]; ++left; } else { From 55086c231acbb8794299d2f143444173de2b85e9 Mon Sep 17 00:00:00 2001 From: w2xi <43wangxi@gmail.com> Date: Sat, 2 Jul 2022 11:14:57 +0800 Subject: [PATCH 16/22] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md=20JavaScript=E9=80=92=E5=BD=92=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 8e35fc9d..83d20df8 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -470,25 +470,14 @@ func invertTree(root *TreeNode) *TreeNode { 使用递归版本的前序遍历 ```javascript var invertTree = function(root) { - //1. 首先使用递归版本的前序遍历实现二叉树翻转 - //交换节点函数 - const inverNode=function(left,right){ - let temp=left; - left=right; - right=temp; - //需要重新给root赋值一下 - root.left=left; - root.right=right; + // 终止条件 + if (!root) { + return null; } - //确定递归函数的参数和返回值inverTree=function(root) - //确定终止条件 - if(root===null){ - return root; - } - //确定节点处理逻辑 交换 - inverNode(root.left,root.right); - invertTree(root.left); - invertTree(root.right); + // 交换左右节点 + const rightNode = root.right; + root.right = invertTree(root.left); + root.left = invertTree(rightNode); return root; }; ``` From 11b701fdb6ba689bdc9f07362e497a4d2ab5eefd Mon Sep 17 00:00:00 2001 From: AronJudge <2286381138@qq.com> Date: Mon, 4 Jul 2022 00:58:56 +0800 Subject: [PATCH 17/22] =?UTF-8?q?0018=20Java=E4=BB=A3=E7=A0=81=E9=83=A8?= =?UTF-8?q?=E5=88=86=E5=A2=9E=E5=8A=A0=E5=89=AA=E6=9E=9D=E6=93=8D=E4=BD=9C?= =?UTF-8?q?,=E4=B8=8D=E7=84=B6Leetcode=E4=B8=8D=E8=83=BD=E9=80=9A=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 6cbd40c2..d0b7fc68 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -140,6 +140,11 @@ class Solution { for (int i = 0; i < nums.length; i++) { + // nums[i] > target 直接返回, 剪枝操作 + if (nums[i] > 0 && nums[i] > target) { + return result; + } + if (i > 0 && nums[i - 1] == nums[i]) { continue; } From 0ee18c392d33c87f86a2de97cb7cd3654736a551 Mon Sep 17 00:00:00 2001 From: w2xi <43wangxi@gmail.com> Date: Wed, 6 Jul 2022 22:01:14 +0800 Subject: [PATCH 18/22] =?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=20JavaScript=E9=80=92=E5=BD=92=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0450.删除二叉搜索树中的节点.md | 57 +++++++++++-------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 3fa2a1c5..3bc8369c 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -456,31 +456,42 @@ func deleteNode(root *TreeNode, key int) *TreeNode { * @param {number} key * @return {TreeNode} */ -var deleteNode = function (root, key) { - if (root === null) - return root; - if (root.val === key) { - if (!root.left) - return root.right; - else if (!root.right) - return root.left; - else { - let cur = root.right; - while (cur.left) { - cur = cur.left; - } - cur.left = root.left; - root = root.right; - delete root; - return root; - } - } - if (root.val > key) - root.left = deleteNode(root.left, key); - if (root.val < key) +var deleteNode = function(root, key) { + if (!root) return null; + if (key > root.val) { root.right = deleteNode(root.right, key); - return root; + return root; + } else if (key < root.val) { + root.left = deleteNode(root.left, key); + return root; + } else { + // 场景1: 该节点是叶节点 + if (!root.left && !root.right) { + return null + } + // 场景2: 有一个孩子节点不存在 + if (root.left && !root.right) { + return root.left; + } else if (root.right && !root.left) { + return root.right; + } + // 场景3: 左右节点都存在 + const rightNode = root.right; + // 获取最小值节点 + const minNode = getMinNode(rightNode); + // 将待删除节点的值替换为最小值节点值 + root.val = minNode.val; + // 删除最小值节点 + root.right = deleteNode(root.right, minNode.val); + return root; + } }; +function getMinNode(root) { + while (root.left) { + root = root.left; + } + return root; +} ``` 迭代 From 85e0d6c85d593339152483a3fea33ab23cdcd5b3 Mon Sep 17 00:00:00 2001 From: AronJudge <2286381138@qq.com> Date: Mon, 11 Jul 2022 11:06:51 +0800 Subject: [PATCH 19/22] =?UTF-8?q?=E6=9B=B4=E6=96=B00347=20=E5=89=8DK?= =?UTF-8?q?=E4=B8=AA=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 由原来的构建小顶堆改为构建大顶堆,减少部分代码逻辑,并增加了注释 通过LeetCode提交代码,修改后的执行时间更快。 --- problems/0347.前K个高频元素.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index a04041cc..0c978b2a 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -141,13 +141,10 @@ class Solution { } Set> entries = map.entrySet(); - // 根据map的value值正序排,相当于一个小顶堆 - PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue()); + // 根据map的value值,构建于一个大顶堆(o1 - o2: 小顶堆, o2 - o1 : 大顶堆) + PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue()); for (Map.Entry entry : entries) { queue.offer(entry); - if (queue.size() > k) { - queue.poll(); - } } for (int i = k - 1; i >= 0; i--) { result[i] = queue.poll().getKey(); From ba081f84a85ff75134c4db551e0e631b86693081 Mon Sep 17 00:00:00 2001 From: AronJudge <2286381138@qq.com> Date: Tue, 12 Jul 2022 11:36:26 +0800 Subject: [PATCH 20/22] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200104.=20=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 代码错误,更正代码,通过LeetCode代码检验。 --- problems/0104.二叉树的最大深度.md | 25 +++++++++++------------ 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index ed27f95d..55980189 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -294,14 +294,13 @@ class solution { /** * 递归法 */ - public int maxdepth(treenode root) { + public int maxDepth(TreeNode root) { if (root == null) { return 0; } - int leftdepth = maxdepth(root.left); - int rightdepth = maxdepth(root.right); - return math.max(leftdepth, rightdepth) + 1; - + int leftDepth = maxDepth(root.left); + int rightDepth = maxDepth(root.right); + return Math.max(leftDepth, rightDepth) + 1; } } ``` @@ -311,23 +310,23 @@ class solution { /** * 迭代法,使用层序遍历 */ - public int maxdepth(treenode root) { + public int maxDepth(TreeNode root) { if(root == null) { return 0; } - deque deque = new linkedlist<>(); + Deque deque = new LinkedList<>(); deque.offer(root); int depth = 0; - while (!deque.isempty()) { + while (!deque.isEmpty()) { int size = deque.size(); depth++; for (int i = 0; i < size; i++) { - treenode poll = deque.poll(); - if (poll.left != null) { - deque.offer(poll.left); + TreeNode node = deque.poll(); + if (node.left != null) { + deque.offer(node.left); } - if (poll.right != null) { - deque.offer(poll.right); + if (node.right != null) { + deque.offer(node.right); } } } From a8e19d60bb371a44296134932b7470825c1fda6a Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Tue, 12 Jul 2022 14:08:50 +0800 Subject: [PATCH 21/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200202.=E5=BF=AB?= =?UTF-8?q?=E4=B9=90=E6=95=B0=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0202.快乐数 Rust版本 --- problems/0202.快乐数.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 0bea0c72..2303765c 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -315,6 +315,36 @@ class Solution { } ``` +Rust: +```Rust +use std::collections::HashSet; +impl Solution { + pub fn get_sum(mut n: i32) -> i32 { + let mut sum = 0; + while n > 0 { + sum += (n % 10) * (n % 10); + n /= 10; + } + sum + } + + pub fn is_happy(n: i32) -> bool { + let mut n = n; + let mut set = HashSet::new(); + loop { + let sum = Self::get_sum(n); + if sum == 1 { + return true; + } + if set.contains(&sum) { + return false; + } else { set.insert(sum); } + n = sum; + } + } +} +``` + C: ```C typedef struct HashNodeTag { From 07ab44ede3fa043184754a638f59e6b76a7c3e0a Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Tue, 12 Jul 2022 15:26:07 +0800 Subject: [PATCH 22/22] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200015.=E4=B8=89?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=200018.=E5=9B=9B=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0015.三数之和 0018.四数之和 Rust版本 --- problems/0015.三数之和.md | 65 +++++++++++++++++++++++++++++++++++ problems/0018.四数之和.md | 45 ++++++++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 4f1d711a..94885b0c 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -554,6 +554,71 @@ func threeSum(_ nums: [Int]) -> [[Int]] { } ``` +Rust: +```Rust +// 哈希解法 +use std::collections::HashSet; +impl Solution { + pub fn three_sum(nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut nums = nums; + nums.sort(); + let len = nums.len(); + for i in 0..len { + if nums[i] > 0 { break; } + if i > 0 && nums[i] == nums[i - 1] { continue; } + let mut set = HashSet::new(); + for j in (i + 1)..len { + if j > i + 2 && nums[j] == nums[j - 1] && nums[j] == nums[j - 2] { continue; } + let c = 0 - (nums[i] + nums[j]); + if set.contains(&c) { + result.push(vec![nums[i], nums[j], c]); + set.remove(&c); + } else { set.insert(nums[j]); } + } + } + result + } +} +``` + +```Rust +// 双指针法 +use std::collections::HashSet; +impl Solution { + pub fn three_sum(nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut nums = nums; + nums.sort(); + let len = nums.len(); + for i in 0..len { + if nums[i] > 0 { return result; } + if i > 0 && nums[i] == nums[i - 1] { continue; } + let (mut left, mut right) = (i + 1, len - 1); + while left < right { + if nums[i] + nums[left] + nums[right] > 0 { + right -= 1; + // 去重 + while left < right && nums[right] == nums[right + 1] { right -= 1; } + } else if nums[i] + nums[left] + nums[right] < 0 { + left += 1; + // 去重 + while left < right && nums[left] == nums[left - 1] { left += 1; } + } else { + result.push(vec![nums[i], nums[left], nums[right]]); + // 去重 + right -= 1; + left += 1; + while left < right && nums[right] == nums[right + 1] { right -= 1; } + while left < right && nums[left] == nums[left - 1] { left += 1; } + } + } + } + result + } +} +``` + C: ```C //qsort辅助cmp函数 diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 2146a114..f6cfad29 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -522,6 +522,51 @@ public class Solution } } ``` + +Rust: +```Rust +impl Solution { + pub fn four_sum(nums: Vec, target: i32) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut nums = nums; + nums.sort(); + let len = nums.len(); + for k in 0..len { + // 剪枝 + if nums[k] > target && (nums[k] > 0 || target > 0) { break; } + // 去重 + if k > 0 && nums[k] == nums[k - 1] { continue; } + for i in (k + 1)..len { + // 剪枝 + if nums[k] + nums[i] > target && (nums[k] + nums[i] >= 0 || target >= 0) { break; } + // 去重 + if i > k + 1 && nums[i] == nums[i - 1] { continue; } + let (mut left, mut right) = (i + 1, len - 1); + while left < right { + if nums[k] + nums[i] > target - (nums[left] + nums[right]) { + right -= 1; + // 去重 + while left < right && nums[right] == nums[right + 1] { right -= 1; } + } else if nums[k] + nums[i] < target - (nums[left] + nums[right]) { + left += 1; + // 去重 + while left < right && nums[left] == nums[left - 1] { left += 1; } + } else { + result.push(vec![nums[k], nums[i], nums[left], nums[right]]); + // 去重 + while left < right && nums[right] == nums[right - 1] { right -= 1; } + while left < right && nums[left] == nums[left + 1] { left += 1; } + left += 1; + right -= 1; + } + } + } + } + result + } +} +``` + Scala: ```scala object Solution {