mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0491.递增子序列.md Scala版本
This commit is contained in:
@ -522,5 +522,39 @@ func findSubsequences(_ nums: [Int]) -> [[Int]] {
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Scala
|
||||||
|
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
import scala.collection.mutable
|
||||||
|
def findSubsequences(nums: Array[Int]): List[List[Int]] = {
|
||||||
|
var result = mutable.ListBuffer[List[Int]]()
|
||||||
|
var path = mutable.ListBuffer[Int]()
|
||||||
|
|
||||||
|
def backtracking(startIndex: Int): Unit = {
|
||||||
|
// 集合元素大于1,添加到结果集
|
||||||
|
if (path.size > 1) {
|
||||||
|
result.append(path.toList)
|
||||||
|
}
|
||||||
|
|
||||||
|
var used = new Array[Boolean](201)
|
||||||
|
// 使用循环守卫,当前层没有用过的元素才有资格进入回溯
|
||||||
|
for (i <- startIndex until nums.size if !used(nums(i) + 100)) {
|
||||||
|
// 如果path没元素或 当前循环的元素比path的最后一个元素大,则可以进入回溯
|
||||||
|
if (path.size == 0 || (!path.isEmpty && nums(i) >= path(path.size - 1))) {
|
||||||
|
used(nums(i) + 100) = true
|
||||||
|
path.append(nums(i))
|
||||||
|
backtracking(i + 1)
|
||||||
|
path.remove(path.size - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
backtracking(0)
|
||||||
|
result.toList
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<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