diff --git a/problems/0077.组合.md b/problems/0077.组合.md index f280c176..58382221 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -675,6 +675,7 @@ func combine(_ n: Int, _ k: Int) -> [[Int]] { ### Scala +暴力: ```scala object Solution { import scala.collection.mutable // 导包 @@ -701,5 +702,34 @@ object Solution { } ``` +剪枝: + +```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 - (k - path.size) + 1)) { + path.append(i) // 先把数字添加进去 + backtracking(n, k, i + 1) // 进行下一步回溯 + path = path.take(path.size - 1) // 回溯完再删除掉刚刚添加的数字 + } + } + + backtracking(n, k, 1) // 执行回溯 + result.toList // 最终返回result的List形式,return关键字可以省略 + } +} +``` + -----------------------