[PythonでLeetCode]電話番号の文字の組み合わせに電話番号の17(M)文字の組み合わせ

トピック:

https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/

文字列が数字だけ2-9が含まれて考えると、それは組み合わせが示されているすべての文字を返すことができます。
(同じ電話キー)、次のように文字にデジタルマップを考えます。
注1は任意のアルファベットに対応していません。

例:

入力: "23"
を出力する:. [ "広告"、 " AE"、 "BD"、 "である"、 "BF"、 "CD"、 "CE"、 "CF"、 "AF"]
説明:
上記もののその答えは、辞書式順序に基づいていますが、あなたは答え出力の順序を選択することができます。

問題解決のためのアイデア

DFS標準ルーチン、注意DFS()の前と処理ラインの後。

コード

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        # - sanity check
        if not digits:
            return []

        # - digit -> chars
        digit_dict = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }

        res = []

        # - dfs
        def dfs(index, s):
            # - return
            if index == len(digits):
                res.append(s)
                return

            # - for every branches
            for c in digit_dict[digits[index]]:
                s += c
                dfs(index+1, s)
                s = s[:-1]
        
        # - from digits[0]
        dfs(0, '')

        return res

おすすめ

転載: www.cnblogs.com/journeyonmyway/p/12543425.html