mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0040.组合总和II.md Scala版本
This commit is contained in:
@ -693,5 +693,37 @@ func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def combinationSum2(candidates: Array[Int], target: Int): List[List[Int]] = {
|
||||
var res = mutable.ListBuffer[List[Int]]()
|
||||
var path = mutable.ListBuffer[Int]()
|
||||
var candidate = candidates.sorted
|
||||
|
||||
def backtracking(sum: Int, startIndex: Int): Unit = {
|
||||
if (sum == target) {
|
||||
res.append(path.toList)
|
||||
return
|
||||
}
|
||||
|
||||
for (i <- startIndex until candidate.size if sum + candidate(i) <= target) {
|
||||
if (!(i > startIndex && candidate(i) == candidate(i - 1))) {
|
||||
path.append(candidate(i))
|
||||
backtracking(sum + candidate(i), i + 1)
|
||||
path = path.take(path.size - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
backtracking(0, 0)
|
||||
res.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