添加 0216.组合总和III.md Scala版本

This commit is contained in:
ZongqinWang
2022-06-02 12:13:52 +08:00
parent f03f8d2b61
commit 7dd463e085

View File

@ -511,5 +511,35 @@ func combinationSum3(_ count: Int, _ targetSum: Int) -> [[Int]] {
}
```
## Scala
```scala
object Solution {
import scala.collection.mutable
def combinationSum3(k: Int, n: Int): List[List[Int]] = {
var result = mutable.ListBuffer[List[Int]]()
var path = mutable.ListBuffer[Int]()
def backtracking(k: Int, n: Int, sum: Int, startIndex: Int): Unit = {
if (sum > n) return // 剪枝如果sum>目标和,就返回
if (sum == n && path.size == k) {
result.append(path.toList)
return
}
// 剪枝
for (i <- startIndex to (9 - (k - path.size) + 1)) {
path.append(i)
backtracking(k, n, sum + i, i + 1)
path = path.take(path.size - 1)
}
}
backtracking(k, n, 0, 1) // 调用递归方法
result.toList // 最终返回结果集的List形式
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>