From 97fc88e533418bf9070bd9fb549a23a2499805b4 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Tue, 7 Jun 2022 16:59:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200046.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 836c3646..ec3adaa7 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -456,6 +456,36 @@ func permute(_ nums: [Int]) -> [[Int]] { } ``` +### Scala + +```scala +object Solution { + import scala.collection.mutable + def permute(nums: Array[Int]): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + + def backtracking(used: Array[Boolean]): Unit = { + if (path.size == nums.size) { + // 如果path的长度和nums相等,那么可以添加到结果集 + result.append(path.toList) + return + } + // 添加循环守卫,只有当当前数字没有用过的情况下才进入回溯 + for (i <- nums.indices if used(i) == false) { + used(i) = true + path.append(nums(i)) + backtracking(used) // 回溯 + path.remove(path.size - 1) + used(i) = false + } + } + + backtracking(new Array[Boolean](nums.size)) // 调用方法 + result.toList // 最终返回结果集的List形式 + } +} +``` -----------------------