【leetcode刷题】17. Letter Combinations of a Phone Number

时间:2019-03-20
本文章向大家介绍【leetcode刷题】17. Letter Combinations of a Phone Number,主要包括【leetcode刷题】17. Letter Combinations of a Phone Number使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

原题链接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/

思路:对于每一步迭代,均输入上一次迭代的结果,如[‘a’,‘b’,‘c’],以及这一次会加在后面的字符串,如’def’,用一个新的列表,遍历上一次答案里的元素,并将新字符串的元素分别贴上去。第一次写入的时候,由于结果还为空,就直接把字符串每一个字符打头生成一个元素。

代码:

class Solution(object):
    def add(self, digit, ans):
        if ans == []:
            for letter in digit:
                ans.append(letter)
            return ans
        tmp = []
        for letter1 in ans:
            for letter2 in digit:
                tmp.append(letter1+letter2)
        return tmp


    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        result = []
        dictionary = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        for digit in digits:
            result = self.add(dictionary[digit], result)
        return result

参考了代码:
https://www.cnblogs.com/chruny/p/4835631.html