mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0078.子集.md Scala版本
This commit is contained in:
@ -373,6 +373,60 @@ func subsets(_ nums: [Int]) -> [[Int]] {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
思路一: 使用本题解思路
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def subsets(nums: Array[Int]): List[List[Int]] = {
|
||||
var result = mutable.ListBuffer[List[Int]]()
|
||||
var path = mutable.ListBuffer[Int]()
|
||||
|
||||
def backtracking(startIndex: Int): Unit = {
|
||||
result.append(path.toList) // 存放结果
|
||||
if (startIndex >= nums.size) {
|
||||
return
|
||||
}
|
||||
for (i <- startIndex until nums.size) {
|
||||
path.append(nums(i)) // 添加元素
|
||||
backtracking(i + 1)
|
||||
path.remove(path.size - 1) // 删除
|
||||
}
|
||||
}
|
||||
|
||||
backtracking(0)
|
||||
result.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
思路二: 将原问题转换为二叉树,针对每一个元素都有**选或不选**两种选择,直到遍历到最后,所有的叶子节点即为本题的答案:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def subsets(nums: Array[Int]): List[List[Int]] = {
|
||||
var result = mutable.ListBuffer[List[Int]]()
|
||||
|
||||
def backtracking(path: mutable.ListBuffer[Int], startIndex: Int): Unit = {
|
||||
if (startIndex == nums.length) {
|
||||
result.append(path.toList)
|
||||
return
|
||||
}
|
||||
path.append(nums(startIndex))
|
||||
backtracking(path, startIndex + 1) // 选择元素
|
||||
path.remove(path.size - 1)
|
||||
backtracking(path, startIndex + 1) // 不选择元素
|
||||
}
|
||||
|
||||
backtracking(mutable.ListBuffer[Int](), 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