LeetCode 17.电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
{'2':'abc','3':'def','4':'ghi',
'5':'jkl','6':'mno','7':'pqrs',
'8':'tuv','9':'wxyz'}

class Solution:
    def letterCombinations(self, digits: str) :
        if len(digits)==0:
            return []
        num_dict = {'2':'abc','3':'def','4':'ghi',
                    '5':'jkl','6':'mno','7':'pqrs',
                    '8':'tuv','9':'wxyz'}
        ret = []
        #self.dfs(digits,num_dict,0,'',ret)
        self.bfs(digits,num_dict,0,ret)
        return ret

    def dfs(self,digits,num_dict,i,cur_str,ans):
        #print(cur_str,i)
        if i>=len(digits):
            ans.append(cur_str)
            return
        for c in num_dict[digits[i]]:
            #cur_str = cur_str+c
            self.dfs(digits,num_dict,i+1,cur_str+c,ans)

    def bfs(self,digits,num_dict,i,ans):
        if i>=len(digits):
            return
        if i==0:
            for c in num_dict[digits[i]]:
                ans.append(c)
        else:
            this = []
            while len(ans)>0:
                a = ans.pop(0)
                for c in num_dict[digits[i]]:
                    this.append(a+c)
            for a in this:
                ans.append(a)

        #print(ans,i)
        self.bfs(digits,num_dict,i+1,ans)
        #print(ans,i)  
posted @ 2020-07-11 14:11  机器狗mo  阅读(143)  评论(0编辑  收藏  举报