Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e734d0a

Browse files
committed
添加 0077.组合.md 剪枝 Scala版本
1 parent 0bdb37d commit e734d0a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎problems/0077.组合.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,7 @@ func combine(_ n: Int, _ k: Int) -> [[Int]] {
675675

676676
### Scala
677677

678+
暴力:
678679
```scala
679680
object Solution {
680681
import scala.collection.mutable // 导包
@@ -701,5 +702,34 @@ object Solution {
701702
}
702703
```
703704

705+
剪枝:
706+
707+
```scala
708+
object Solution {
709+
import scala.collection.mutable // 导包
710+
def combine(n: Int, k: Int): List[List[Int]] = {
711+
var result = mutable.ListBuffer[List[Int]]() // 存放结果集
712+
var path = mutable.ListBuffer[Int]() //存放符合条件的结果
713+
714+
def backtracking(n: Int, k: Int, startIndex: Int): Unit = {
715+
if (path.size == k) {
716+
// 如果path的size == k就达到题目要求,添加到结果集,并返回
717+
result.append(path.toList)
718+
return
719+
}
720+
// 剪枝优化
721+
for (i <- startIndex to (n - (k - path.size) + 1)) {
722+
path.append(i) // 先把数字添加进去
723+
backtracking(n, k, i + 1) // 进行下一步回溯
724+
path = path.take(path.size - 1) // 回溯完再删除掉刚刚添加的数字
725+
}
726+
}
727+
728+
backtracking(n, k, 1) // 执行回溯
729+
result.toList // 最终返回result的List形式,return关键字可以省略
730+
}
731+
}
732+
```
733+
704734
-----------------------
705735
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /