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 7dd463e

Browse files
committed
添加 0216.组合总和III.md Scala版本
1 parent f03f8d2 commit 7dd463e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎problems/0216.组合总和III.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,5 +511,35 @@ func combinationSum3(_ count: Int, _ targetSum: Int) -> [[Int]] {
511511
}
512512
```
513513

514+
## Scala
515+
516+
```scala
517+
object Solution {
518+
import scala.collection.mutable
519+
def combinationSum3(k: Int, n: Int): List[List[Int]] = {
520+
var result = mutable.ListBuffer[List[Int]]()
521+
var path = mutable.ListBuffer[Int]()
522+
523+
def backtracking(k: Int, n: Int, sum: Int, startIndex: Int): Unit = {
524+
if (sum > n) return // 剪枝,如果sum>目标和,就返回
525+
if (sum == n && path.size == k) {
526+
result.append(path.toList)
527+
return
528+
}
529+
// 剪枝
530+
for (i <- startIndex to (9 - (k - path.size) + 1)) {
531+
path.append(i)
532+
backtracking(k, n, sum + i, i + 1)
533+
path = path.take(path.size - 1)
534+
}
535+
}
536+
537+
backtracking(k, n, 0, 1) // 调用递归方法
538+
result.toList // 最终返回结果集的List形式
539+
}
540+
}
541+
```
542+
543+
514544
-----------------------
515545
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

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