首页 > 其他 > 详细

17. Letter Combinations of a Phone Number

时间:2016-02-25 01:32:03      阅读:177      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/zhuifengjingling/p/5215564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!