17. 电话号码的字母组合
2022-07-18 本文已影响0人
邦_
class Solution {
let map :Dictionary<Character,Array<Character>> = [
"2" : ["a","b","c"],
"3" : ["d","e","f"],
"4" : ["g","h","i"],
"5" : ["j","k","l"],
"6" : ["m","n","o"],
"7" : ["p","q","r","s"],
"8" : ["t","u","v"],
"9" : ["w","x","y","z"]
]
var ans = Array<String>()
var tempStrArray = Array<Character>()
func letterCombinations(_ digits: String) -> [String] {
let len = digits.count
if len == 0 {
return []
}
tempStrArray = Array.init(repeating: " ", count: len)
dfs(0,Array(digits))
return ans
}
func dfs(_ index:Int,_ digitsArray:Array<Character>) {
let len = digitsArray.count
//说明到达了底部,可以获得一个正确的解
if index == len {
ans.append(String.init(tempStrArray))
return
}
let key = digitsArray[index]
let array = map[key]!
//枚举出来这一层
for c in array {
tempStrArray[index] = c
dfs(index + 1,digitsArray)
}
}
}
改造版本
let map :Dictionary<Character,Array<Character>> = [
"2" : ["a","b","c"],
"3" : ["d","e","f"],
"4" : ["g","h","i"],
"5" : ["j","k","l"],
"6" : ["m","n","o"],
"7" : ["p","q","r","s"],
"8" : ["t","u","v"],
"9" : ["w","x","y","z"]
]
func letterCombinations(_ digits: String) -> [String] {
let len = digits.count
if len == 0 {
return []
}
var ans = Array<String>()
var tempStrArray : Array<Character> = Array.init(repeating: " ", count: len)
dfs(0,Array(digits),&ans,&tempStrArray)
return ans
}
func dfs(_ index:Int,_ digitsArray:Array<Character>, _ ans:inout Array<String>, _ tempStrArray: inout Array<Character>) {
let len = digitsArray.count
//说明到达了底部,可以获得一个正确的解
if index == len {
ans.append(String.init(tempStrArray))
return
}
let key = digitsArray[index]
let array = map[key]!
//枚举出来这一层
for c in array {
tempStrArray[index] = c
dfs(index + 1,digitsArray,&ans,&tempStrArray)
}
}