17. 电话号码的字母组合 Python

文章目录

  • 一、题目描述
      • 示例 1
      • 示例 2
      • 示例 3
  • 二、代码
  • 三、解题思路


一、题目描述

给定一个仅包含数字 2-9的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1不对应任何字母。
17. 电话号码的字母组合 Python_第1张图片

示例 1

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2

输入:digits = ""
输出:[]

示例 3

输入:digits = "2"
输出:["a","b","c"]

提示:0 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。

二、代码

代码如下:

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
            number = [[""],[""],["a","b","c"],["d","e","f"],["g","h","i"],["j","k","l"],["m","n","o"],["p","q","r","s"],["t","u","v"],["w","x","y","z"]]
            result = []
            listD = []
            count = []
            index = 0
            for e in digits:
                listD.append(e)
                count.append(int(e))
            if digits == "":
                return []
            if len(digits) == 1:
                print(number[int(digits[0])])
                return number[int(digits[0])]
            if len(digits) == 2:
                for e in number[count[index]]:
                    for e1 in number[count[index+1]]:
                        s = e + e1
                        result.append(s)
                return result
            if len(digits) == 3:
                for e in number[count[index]]:
                    for e1 in number[count[index+1]]:
                        for e2 in number[count[index + 2]]:
                            s = e + e1 + e2
                            result.append(s)
                return result
            if len(digits) == 4:
                for e in number[count[index]]:
                    for e1 in number[count[index+1]]:
                        for e2 in number[count[index + 2]]:
                            for e3 in number[count[index + 3]]:
                                s = e + e1 + e2 +e3
                                result.append(s)
                return result

三、解题思路

PS:个人能力有限,不考虑时间空间最优。
写在前面,本题采用了暴力for循环方法,且只适用于0 <= digits.length <= 4的情况。
分类讨论,分别看输入的数字是几位数,然后在进行对应个数的for循环,例如输入的数字为3位数,则进行3次for循环。

你可能感兴趣的:(LeetCode中等难度题集,python,算法)