diff --git a/problems/0078.子集.md b/problems/0078.子集.md index e1c52b5b..3fc396a2 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -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 + } +} +``` + -----------------------