1. 程式人生 > >17. 電話號碼的字母組合(swift)

17. 電話號碼的字母組合(swift)

給定一個僅包含數字 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()
        }
    }
}