快乐的LeetCode --- 17. 电话号码的字母组合

题目描述:

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
在这里插入图片描述
示例:

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

解题思路1:

代码1目前只能实现针对两个字符及以下的情况


代码1:

class Solution(object):
    def keys(self, str_count):
        if str_count == '2':
            return "abc"
        if str_count == '3':
            return "def"
        if str_count == '4':
            return "ghi"
        if str_count == '5':
            return "jkl"
        if str_count == '6':
            return "mno"
        if str_count == '7':
            return "pqrs"
        if str_count == '8':
            return "tuv"
        if str_count == '9':
            return "wxyz"

    def letterCombinations(self, digits):
        num = []   # num中存放的是字符串分离开来的单个字符,对比官方代码发现,该功能是可以省略
        number = len(digits)
        res = []   # res中存放的是组合之后的结果
        if number == 1:
            num.append(self.keys(digits[0][len(digits[0])-1]))
            for j in range(len(num[0])):
                res.append(num[0][j])
            return res

        for i in range(number):
            num.append(self.keys(digits[i]))

        for i in range(len(num)-1):
            k = 0
            while k < len(num[i]):
                for j in range(len(num[i+1])):
                    res.append(num[i][k]+num[i+1][j])
                k += 1
        return res

解题思路2: 回溯

来源于:LeetCode官方题解
  回溯是一种通过穷举所有可能情况来找到所有解的算法。如果一个候选解最后被发现并不是可行解,回溯算法会舍弃它,并在前面的一些步骤做出一些修改,并重新尝试找到可行解。

  给出如下回溯函数 backtrack(combination, next_digits) ,它将一个目前已经产生的组合 combination 和接下来准备要输入的数字 next_digits 作为参数。

如果没有更多的数字需要被输入,那意味着当前的组合已经产生好了。
如果还有数字需要被输入:
遍历下一个数字所对应的所有映射的字母。
将当前的字母添加到组合最后,也就是 combination = combination + letter
重复这个过程,输入剩下的数字: backtrack(combination + letter, next_digits[1:])
在这里插入图片描述


代码2:

class Solution:
    def letterCombinations(self, digits):
        phone = {'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']}

        def backtrack(combination, next_digits):
            # if there is no more digits to check
            if len(next_digits) == 0:
                # the combination is done
                output.append(combination)
            # if there are still digits to check
            else:
                # iterate over all letters which map
                # the next available digit
                for letter in phone[next_digits[0]]:
                    # append the current letter to the combination
                    # and proceed to the next digits
                    backtrack(combination + letter, next_digits[1:])

        output = []
        if digits:
            backtrack("", digits)
        return output

题目来源:

https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章