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] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200491.=E9=80=92=E5=A2=9E?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=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/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 + } +} +``` + -----------------------