zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    将博客搬至CSDN
    JAVA代码备注
    清空数据库SQL
    实战ASP.NET访问共享文件夹(含详细操作步骤)
    我希望我知道的七个JavaScript技巧 译(转)
    ASP.NET获取客户端网卡使用的MAC地址信息
    JS中offsetTop、clientTop、scrollTop、offsetTop各属性介绍
    JS屏幕距离参数
    jQuery插件开发精品教程,让你的jQuery提升一个台阶
    jQuery编程的最佳实践
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14525329.html
Copyright © 2011-2022 走看看