算法練習--LeetCode--17. Letter Combinations of a Phone Number: 100%

17. Letter Combinations of a Phone Numbergit

Medium數組

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.緩存

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.bash

1o-o_ 2abc 3defapp

4ghi_ 5jkl 6mnoui

7pqrs 8tuv 9wxyzspa

*+___ 0___ #↑__code

除了0的第一個「」之外的位置的「」是爲了對齊cdn

我以爲上面那玩意兒不如圖

Example:blog

Input: "23"

Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

大意是指要把輸入的數字按照手機鍵盤的映射關係轉成可能的字符串

  • 不要有重複的
  • 不用在乎字符串順序(輸出結果數組的排序)

Note:

雖然題目中給出輸入數字在[2, 9],實測(2019-01-05) 01也有對應的映射關係

0 => " "
1 => "*"
複製代碼

基本分析:

  • 要求長度爲n的結果,首先要求長度爲n-1的結果!
  • n == 1 時候結果是已知的
"0" : [" "],
        "1" : ["*"],
        "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(s: String) -> [String] {
  if s 爲空字符串, return 空數組
    if cache 不包含 s {
      cache[s] = cache[s的第一個字符] * letterCombinations(s除了第一字符之外剩下的部分的結果)
    }
  return cache[s]
}
複製代碼

代碼

// Swift Code
class Solution {
    var cache: [String : [String]] = [
        "0" : [" "],
        "1" : ["*"],
        "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] {
        if digits.isEmpty { return [] }
        if !cache.keys.contains(digits) {
            cache[digits] = letterCombinations(String(digits.prefix(1))).flatMap({ (s) -> [String] in
                letterCombinations(String(digits.suffix(digits.count - 1))).map { s + $0 }
            })
        }
        return cache[digits]!
    }
}
複製代碼

TestCase

  • ""
  • "23"
  • "203"
  • "213"
相關文章
相關標籤/搜索