From 2f0a1830377fe38fed12aba3bfd38424b9c67108 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 2 Jun 2022 16:28:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200017.=E7=94=B5=E8=AF=9D?= =?UTF-8?q?=E5=8F=B7=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88?= =?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 31 ++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 94136565..f638349d 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -557,6 +557,37 @@ func letterCombinations(_ digits: String) -> [String] { } ``` +## Scala: + +```scala +object Solution { + import scala.collection.mutable + def letterCombinations(digits: String): List[String] = { + var result = mutable.ListBuffer[String]() + if(digits == "") return result.toList // 如果参数为空,返回空结果集的List形式 + var path = mutable.ListBuffer[Char]() + // 数字和字符的映射关系 + val map = Array[String]("", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz") + + def backtracking(index: Int): Unit = { + if (index == digits.size) { + result.append(path.mkString) // mkString语法:将数组类型直接转换为字符串 + return + } + var digit = digits(index) - '0' // 这里使用toInt会报错!必须 -'0' + for (i <- 0 until map(digit).size) { + path.append(map(digit)(i)) + backtracking(index + 1) + path = path.take(path.size - 1) + } + } + + backtracking(0) + result.toList + } +} +``` + -----------------------