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] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200090.=E5=AD=90=E9=9B=86II.?= =?UTF-8?q?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 + } +} +``` -----------------------