Note: Although the answers above are arranged in lexicographical order, you can choose the order in which the answers are output.
Two, algorithm example
Ideas
The idea to solve this problem is relatively simple. Each number in a string has multiple letters, for example, 2 corresponds to: 3 abc, 3 corresponds to 3 def, 4 corresponds to 3 ghi, then 234 corresponds to 3 * 3 * 3 The combination of clocks, boiled down to the code, is a three-layer for loop. In other words, digits.count determines how many levels of for loops, then the corresponding N levels of for loops are nested, and it is better to use recursive methods.
The construction of the recursive function is still based on the idea of the for loop. The difference is the exit mechanism of the recursive function, the combination of the corresponding letters and the collection conditions; and the processing of the index of the sub-loop.
let matchTable:[Int:[String]]=[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"]]funcletterCombinations(_ digits:String)->[String]{
if digits ==""{
// 避免map的时候返回 [""]return[]}// Set中任何元素只出现一次var ret:Set<String>=[]var i =0while i <5000{
var str =""for c in digits {
let val =Int(String(c))!// 取随机内容
str += matchTable[val]!.randomElement()!}
ret.insert(str)
i +=1}return ret.map{
(str)->Stringinreturn str
}}