leetcode 17. Letter Combinations of a Phone Number

Description: Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Link: Letter Combination of a Phone Number

Examples:

Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:
Input: digits = ""
Output: []

Example 3:
Input: digits = "2"
Output: ["a","b","c"]

思路: 每个数字有对应的字母,输入数字,返回所有可能的字母组合。所以最直接的方法就是循环。

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if digits == "":
            return []
        digit_dict = dict()
        digit_dict["2"] = ['a','b','c']
        digit_dict["3"] = ['d','e','f']
        digit_dict["4"] = ['g','h','i']
        digit_dict["5"] = ['j','k','l']
        digit_dict["6"] = ['m','n','o']
        digit_dict["7"] = ['p','q','r','s']
        digit_dict["8"] = ['t','u','v']
        digit_dict["9"] = ['w','x','y','z']
        
        rlist = ['']
        for d in digits:
            rlist = [w+c for c in digit_dict[d] for w in rlist]
        return rlist     

题目被划分在DFS中,所以用DFS:

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        digit_dict = {'2' : "abc", '3' : "def", '4' : "ghi", '5' : "jkl", '6' : "mno", '7' : "pqrs", '8' : "tuv", '9' : "wxyz"}
        
        res = []
        self.dfs(digits, 0, res, '', digit_dict)
        return res
    
    def dfs(self, digits, index, res, path, digit_dict):
        if index == len(digits):
            if path != "":
                res.append(path)
            return
        for j in digit_dict[digits[index]]:
            self.dfs(digits, index+1, res, path+j, digit_dict)

日期: 2021-03-12

Feel very guilty that I didn't focus on research and learning new things these 40 days since 2.3 submission. now turn back to solve problems.

posted @ 2021-03-12 17:42  summer_mimi  阅读(53)  评论(0)    收藏  举报