mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 0039.组合总和.md Scala版本
This commit is contained in:
@ -502,5 +502,35 @@ func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def combinationSum(candidates: Array[Int], target: Int): List[List[Int]] = {
|
||||
var result = mutable.ListBuffer[List[Int]]()
|
||||
var path = mutable.ListBuffer[Int]()
|
||||
|
||||
def backtracking(sum: Int, index: Int): Unit = {
|
||||
if (sum == target) {
|
||||
result.append(path.toList) // 如果正好等于target,就添加到结果集
|
||||
return
|
||||
}
|
||||
// 应该是从当前索引开始的,而不是从0
|
||||
// 剪枝优化:添加循环守卫,当sum + c(i) <= target的时候才循环,才可以进入下一次递归
|
||||
for (i <- index until candidates.size if sum + candidates(i) <= target) {
|
||||
path.append(candidates(i))
|
||||
backtracking(sum + candidates(i), i)
|
||||
path = path.take(path.size - 1)
|
||||
}
|
||||
}
|
||||
|
||||
backtracking(0, 0)
|
||||
result.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user