【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

猜你喜欢

转载自blog.csdn.net/weixin_39746008/article/details/88694120