17. Letter Combinations of a Phone Number

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了17. Letter Combinations of a Phone Number相关的知识,希望对你有一定的参考价值。

Given a digit string, 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.

技术分享

Input:Digit string "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.

AC代码:

class Solution(object):
    def letterCombinations(self, digits):
        if not digits: return []
        ret_list = []
        letters_list = (0, 1, abc, def, ghi, jkl, mno, pqrs, tuv, wxyz)

        def backtracing(letters_list, digits, ret_list, index, current):
            # boundary condition, recurse to the deepest
            if index == len(digits):
                ret_list.append(current)
                return
            for v in letters_list[int(digits[index])]:
                backtracing(letters_list, digits, ret_list, index + 1, current + v)

        backtracing(letters_list, digits, ret_list, 0, ‘‘)
        return ret_list

此方法用了经典的回溯法进行递归查找。

还可以用迭代的方式进行查找:

class Solution(object):
    # version iteration, use reduce
    def letterCombinations(self, digits):
        if not digits: return []
        letters_list = (0, 1, abc, def, ghi, jkl, mno, pqrs, tuv, wxyz)
        return reduce(lambda ret_list, index: [e + v for e in ret_list for v in letters_list[int(index)]], digits, [‘‘])

利用reduce函数,其核心代码只有一行,注意reduce第三个参数一定要给初始值 [‘‘]。

随着第一种方法递归深度的增加,效率会变得越来越差,所以推荐第二种方法,既优雅效率也高。

 

以上是关于17. Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number