添加 0077.组合.md Scala版本

This commit is contained in:
ZongqinWang
2022-06-02 10:05:46 +08:00
parent f03f8d2b61
commit 0bdb37d7fa

View File

@ -673,5 +673,33 @@ func combine(_ n: Int, _ k: Int) -> [[Int]] {
}
```
### Scala
```scala
object Solution {
import scala.collection.mutable // 导包
def combine(n: Int, k: Int): List[List[Int]] = {
var result = mutable.ListBuffer[List[Int]]() // 存放结果集
var path = mutable.ListBuffer[Int]() //存放符合条件的结果
def backtracking(n: Int, k: Int, startIndex: Int): Unit = {
if (path.size == k) {
// 如果path的size == k就达到题目要求添加到结果集并返回
result.append(path.toList)
return
}
for (i <- startIndex to n) { // 遍历从startIndex到n
path.append(i) // 先把数字添加进去
backtracking(n, k, i + 1) // 进行下一步回溯
path = path.take(path.size - 1) // 回溯完再删除掉刚刚添加的数字
}
}
backtracking(n, k, 1) // 执行回溯
result.toList // 最终返回result的List形式return关键字可以省略
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>