[Leetcode] 17. Letter Combinations of a Phone Number

来源:互联网 发布:武工队后勤部淘宝 编辑:程序博客网 时间:2024/06/05 14:47

Problem:

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.

思路:
本题其实就是列举若干个集合间组合的所有情况。可以用迭代的方法完成。迭代的方法如下:令当前数字与之前的所有情况result list进行组合,然后再把组合得到的结果赋值给result list,实现迭代。

Solution:

class Solution(object):    digitlist = []    count = 97    i = 0    for i in xrange(10):        tmpl = []        if i == 0 or i == 1:            digitlist.append(tmpl)            continue        elif i ==7 or i == 9:            num = 4        else:            num = 3        j = 0        for j in xrange(num):            tmpl.append(chr(count))            count += 1        digitlist.append(tmpl)    def letterCombinations(self, digits):        """        :type digits: str        :rtype: List[str]        """        if len(digits) == 0 :            return []        result = [""]        for s in digits:            num = int(s)            if num >=2 and num <= 9:                tmplist = []            else:                continue            for d in self.digitlist[num]:                for item in result:                    tmplist.append(item+d)            result = tmplist        return result
0 0
原创粉丝点击