码迷,mamicode.com
首页 > 其他好文 > 详细

17. Letter Combinations of a Phone Number

时间:2016-02-25 01:34:28      阅读:123      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!