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第三个参数一定要给初始值 ['']。

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

原文地址:https://www.cnblogs.com/zhuifengjingling/p/5215564.html