算法算法提高之LeetCode刷题

Leetcode - No.17 Letter Combinat

2018-10-08  本文已影响3人  KidneyBro

Description

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

字典穷举匹配问题,本解答使用暴力穷举。

1(   )  2(abc)  3(def)
4(ghi)  5(jkl)  6(mno)
7(pqrs) 8(tuv)  9(wxyz)
*( + )  0(   )  #(shift)
E.g 1:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
import copy
class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        res = []
        if not digits:
            return res
        digit_mapping = {'2':"abc", '3':"def", '4':"ghi", '5':"jkl", '6':"mno", '7':"pqrs", '8':"tuv", '9':"wxyz"}
        if len(digits) == 1:
            return list(digit_mapping[digits])
        if "1" in digits:
            return []
        length = len(digits)
        init_sub_str = digit_mapping[digits[0]]
        for init_sub_char in init_sub_str:
            self.combine(init_sub_char, digit_mapping, 1, length, digits, res)
        
        return res
上一篇下一篇

猜你喜欢

热点阅读