From d2e9927e97519621ba04f1e3d82684ed3cfafc5f Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Fri, 3 Jun 2022 09:46:09 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200039.=E7=BB=84?= =?UTF-8?q?=E5=90=88=E6=80=BB=E5=92=8C.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index e10a827f..ca6312f5 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -502,5 +502,35 @@ func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { } ``` +## Scala + +```scala +object Solution { + import scala.collection.mutable + def combinationSum(candidates: Array[Int], target: Int): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + + def backtracking(sum: Int, index: Int): Unit = { + if (sum == target) { + result.append(path.toList) // 如果正好等于target,就添加到结果集 + return + } + // 应该是从当前索引开始的,而不是从0 + // 剪枝优化:添加循环守卫,当sum + c(i) <= target的时候才循环,才可以进入下一次递归 + for (i <- index until candidates.size if sum + candidates(i) <= target) { + path.append(candidates(i)) + backtracking(sum + candidates(i), i) + path = path.take(path.size - 1) + } + } + + backtracking(0, 0) + result.toList + } +} +``` + + -----------------------
From 301a703ece704650eeb0bfd1eb8ef2079ee274b5 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Fri, 3 Jun 2022 15:24:28 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200040.=E7=BB=84?= =?UTF-8?q?=E5=90=88=E6=80=BB=E5=92=8CII.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 34ac64e6..6b635f8c 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -693,5 +693,37 @@ func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] { } ``` + +## Scala + +```scala +object Solution { + import scala.collection.mutable + def combinationSum2(candidates: Array[Int], target: Int): List[List[Int]] = { + var res = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + var candidate = candidates.sorted + + def backtracking(sum: Int, startIndex: Int): Unit = { + if (sum == target) { + res.append(path.toList) + return + } + + for (i <- startIndex until candidate.size if sum + candidate(i) <= target) { + if (!(i > startIndex && candidate(i) == candidate(i - 1))) { + path.append(candidate(i)) + backtracking(sum + candidate(i), i + 1) + path = path.take(path.size - 1) + } + } + } + + backtracking(0, 0) + res.toList + } +} +``` + -----------------------