zoukankan      html  css  js  c++  java
  • 算法练习--LeetCode--17. Letter Combinations of a Phone Number

    1. Letter Combinations of a Phone Number
      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.

    1o-o_ 2abc 3def
    4ghi_ 5jkl 6mno
    7pqrs 8tuv 9wxyz
    *+___ 0___ #↑__

    除了0的第一个“”以外的位置的“”是为了对齐

     
    我觉得上面那玩意儿不如图

    Example:

    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"
  • 相关阅读:
    写点别的,关于二维码,由印美图想到的
    600篇以上博客,才能进阶到精通的地步,奋斗吧少年
    写博客真的很枯燥,更麻烦的是我还不会MD,排版太不友好了啊。
    对sqlserver存储过程合游标的一些理解
    sqlserver的存储过程
    Apache负载均衡配置
    组合模式解决原型创建对象传参和共享难题
    原型创建对象
    构造函数创建对象
    jQuery实现瀑布流的简单方法
  • 原文地址:https://www.cnblogs.com/kongkaikai/p/10223216.html
Copyright © 2011-2022 走看看