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 5ac414f

Browse files
committed
添加 0077.组合优化.md Scala版本
1 parent e734d0a commit 5ac414f

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎problems/0077.组合优化.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,5 +346,34 @@ func combine(_ n: Int, _ k: Int) -> [[Int]] {
346346
}
347347
```
348348

349+
Scala:
350+
351+
```scala
352+
object Solution {
353+
import scala.collection.mutable // 导包
354+
def combine(n: Int, k: Int): List[List[Int]] = {
355+
var result = mutable.ListBuffer[List[Int]]() // 存放结果集
356+
var path = mutable.ListBuffer[Int]() //存放符合条件的结果
357+
358+
def backtracking(n: Int, k: Int, startIndex: Int): Unit = {
359+
if (path.size == k) {
360+
// 如果path的size == k就达到题目要求,添加到结果集,并返回
361+
result.append(path.toList)
362+
return
363+
}
364+
// 剪枝优化
365+
for (i <- startIndex to (n - (k - path.size) + 1)) {
366+
path.append(i) // 先把数字添加进去
367+
backtracking(n, k, i + 1) // 进行下一步回溯
368+
path = path.take(path.size - 1) // 回溯完再删除掉刚刚添加的数字
369+
}
370+
}
371+
372+
backtracking(n, k, 1) // 执行回溯
373+
result.toList // 最终返回result的List形式,return关键字可以省略
374+
}
375+
}
376+
```
377+
349378
-----------------------
350379
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

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