【leetcode(python) 17. Letter Combinations of a Phone Number详解

Description

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.
在这里插入图片描述

Example

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

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

题目大意

像九宫格的按键一样, 一个数字对应一字符串,按不同的数字能得到对应的字母组合

解题思路

如示例’23’, ‘2’对应’abc’,‘3’对应’def’
第一层’2’得到’a’,‘b’,‘c’
第二层在’2’的基础’a’,‘b’,‘c’上分别加上’d’,‘e’,‘f’
首先’a’ + ‘d’,‘e’,‘f’ = ‘ad’,‘ae’,‘af’
再看’b’ + ‘d’,‘e’,‘f’ = ‘bd’,‘be’,‘bf’
最后’c’ + ‘d’,‘e’,‘f’ = ‘cd’,‘ce’,‘cf’

如果’234’, 在’23’基础上加上’4’对应的’g’,‘h’,i’
所以
‘ad’,‘ae’,‘af’ + ‘g’ = ‘adg’,‘aeg’,‘afg’
‘ad’,‘ae’,‘af’ + ‘h’ = ‘adh’,‘aeh’,‘afh’
‘ad’,‘ae’,‘af’ + ‘i’ = ‘adi’,‘aei’,‘afi’

所以递归就能实现了

code

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        
        self.dic=['','1','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
        
        if len(digits) == 0:
            return []
            
        res = ['']
        for digit in digits:
            res = self.Combinations(int(digit), res)
        return res
            
    def Combinations(self, digit, res):
        return [i+j for i in res for j in self.dic[digit]]

Runtime:36ms

参考较优解

code

class Solution:
    keymap = {
        2: "abc",
        3: "def",
        4: "ghi",
        5: "jkl",
        6: "mno",
        7: "pqrs",
        8: "tuv",
        9: "wxyz"
    }
    
    res = []
    digits = ""
    
    def buildletters(self, i, tmpstr):
        if i == len(self.digits):
            if tmpstr:
                self.res.append(tmpstr)
            return
        for c in self.keymap[int(self.digits[i])]:
            self.buildletters(i+1, tmpstr+c)

    def letterCombinations(self, digits: str) -> List[str]:
        self.res = []
        self.digits = digits
        self.buildletters(0, "")
        return self.res

Runtime:28ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值