LeetCode-【回溯】电话号码的字母组合

题目描述LeetCode-【回溯】电话号码的字母组合_第1张图片

LeetCode-【回溯】电话号码的字母组合_第2张图片

在这里插入图片描述

题目分析

此题引出 ” 回溯 “的模板代码

python实现

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        '''
        # 队列
        if not digits:return []
        phone = ["abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
        queue = [""]	#初始化队列
        for digit in digits:
            for _ in range(len(queue)):
                tmp = queue.pop(0)
                for letter in phone[ord(digit)-ord('2')]:
                    queue.append(tmp+letter)
        return queue
        '''

        # 回溯
        if not digits:return []
        res = []
        phone = ["abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
        def backtrack(combination:str, nextdigit:str):
            '''
            combination : 历史值
            nextdigit: 剩余值
            '''
            if len(nextdigit)==0:
                res.append(combination)
                return
            digit = nextdigit[0]
            for letter in phone[ord(digit)-ord('2')]:
                backtrack(combination+letter, nextdigit[1:])
        
        backtrack("",digits)
        return res

代码性能

LeetCode-【回溯】电话号码的字母组合_第3张图片

你可能感兴趣的:(leetcode,算法,职场和发展)