leetcode 每日一题 17. 电话号码的字母组合

Posted nil_f

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 每日一题 17. 电话号码的字母组合相关的知识,希望对你有一定的参考价值。

回溯法

思路:

通过回溯的思维,递归调用枚举出所有可能。

class Solution:
    def letterCombinations(self, digits):
        phone = {\'2\': [\'a\', \'b\', \'c\'],
                 \'3\': [\'d\', \'e\', \'f\'],
                 \'4\': [\'g\', \'h\', \'i\'],
                 \'5\': [\'j\', \'k\', \'l\'],
                 \'6\': [\'m\', \'n\', \'o\'],
                 \'7\': [\'p\', \'q\', \'r\', \'s\'],
                 \'8\': [\'t\', \'u\', \'v\'],
                 \'9\': [\'w\', \'x\', \'y\', \'z\']}
                
        def backtrack(combination, next_digits):
            if len(next_digits) == 0:
                output.append(combination)
            else:
                for letter in phone[next_digits[0]]:
                    backtrack(combination + letter, next_digits[1:])
                    
        output = []
        if digits:
            backtrack("", digits)
        return output

 

以上是关于leetcode 每日一题 17. 电话号码的字母组合的主要内容,如果未能解决你的问题,请参考以下文章