mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0077.组合.md Scala版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user