diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 32b1347e..9e7415be 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -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形式 + } +} +``` + + -----------------------