Leetcode 17. 电话号码的字母组合 ---- python

1. 题目描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
在这里插入图片描述
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

2. 解题思路

可用树的思想
在这里插入图片描述

3. 代码实现

class Solution(object):
    def letterCombinations(self, digits):
        if digits == '':
            return []
        #以字典的形式存储
        hash_table = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        res = ['']
        for i in digits:
            length = len(hash_table[i])
            temp = res
            res = []
            for k in range(len(temp)):
                for j in range(length):
                    value = temp[k] + hash_table[i][j]
                    res.append(value)
        return res
发布了77 篇原创文章 · 获赞 9 · 访问量 6760

猜你喜欢

转载自blog.csdn.net/u013075024/article/details/93885528