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 d2e9927

Browse files
committed
添加 0039.组合总和.md Scala版本
1 parent f03f8d2 commit d2e9927

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎problems/0039.组合总和.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,5 +502,35 @@ func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
502502
}
503503
```
504504

505+
## Scala
506+
507+
```scala
508+
object Solution {
509+
import scala.collection.mutable
510+
def combinationSum(candidates: Array[Int], target: Int): List[List[Int]] = {
511+
var result = mutable.ListBuffer[List[Int]]()
512+
var path = mutable.ListBuffer[Int]()
513+
514+
def backtracking(sum: Int, index: Int): Unit = {
515+
if (sum == target) {
516+
result.append(path.toList) // 如果正好等于target,就添加到结果集
517+
return
518+
}
519+
// 应该是从当前索引开始的,而不是从0
520+
// 剪枝优化:添加循环守卫,当sum + c(i) <= target的时候才循环,才可以进入下一次递归
521+
for (i <- index until candidates.size if sum + candidates(i) <= target) {
522+
path.append(candidates(i))
523+
backtracking(sum + candidates(i), i)
524+
path = path.take(path.size - 1)
525+
}
526+
}
527+
528+
backtracking(0, 0)
529+
result.toList
530+
}
531+
}
532+
```
533+
534+
505535
-----------------------
506536
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

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