给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
![]()
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
理解:深度优先算法。
class Solution {
func letterCombinations(_ digits: String) -> [String] {
if digits.count == 0 {
return []
}
let dic = ["2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"]
var temp = ""
var res = [String]()
dfs(digits, 0, temp, &res, dic)
return res
}
func dfs(_ digits:String, _ idx:Int, _ temp:String, _ res:inout [String], _ dic:Dictionary<String, String>) {
if idx == digits.count {
res.append(temp)
return
}
var t:String = temp
let num = String(digits[digits.index(digits.startIndex, offsetBy: idx)])
for i in 0...dic[num]!.count-1 {
let indexI = dic[num]!.index(dic[num]!.startIndex, offsetBy: i)
let subString = dic[num]![indexI]
t.append(subString)
dfs(digits, idx+1, t, &res, dic)
t.removeLast()
}
}
}

本文介绍了一个算法问题,即给定一个仅包含数字2-9的字符串,如何返回所有可能的字母组合。通过深度优先搜索算法,文章展示了如何利用数字到字母的映射,递归地生成所有可能的组合。
187

被折叠的 条评论
为什么被折叠?



