添加 0090.子集II.md Scala版本

This commit is contained in:
ZongqinWang
2022-06-05 14:13:41 +08:00
parent ccfb805417
commit b353018948

View File

@ -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
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>