17. 电话号码的字母组合

本文介绍了一个使用回溯法解决电话号码字母组合问题的Python实现。通过构建排列树,每次添加下一位数字对应的字母来生成所有可能的组合。文章详细展示了递归回溯函数的工作原理,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个用回溯法,树的结构是排列树。

节点生枝的方式就是添加下一位数字对应的字母。

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        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']}
                # combination 记录临时的组合
                # next_digits 记录的剩下的数字
        def backtrack(combination, next_digits):
            # 得到可行解
            if len(next_digits) == 0:
                # the combination is done
                output.append(combination)
            # 继续搜索
            else:
                # 从剩下的数字对应的字母里让组合里添加
                for letter in phone[next_digits[0]]:
                    # append the current letter to the combination
                    # and proceed to the next digits
                    backtrack(combination + letter, next_digits[1:])
                    
        output = []
        if digits:
            backtrack("", digits)
        return output

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值