zoukankan      html  css  js  c++  java
  • 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)  
    
  • 相关阅读:
    poj1182 食物链
    poj1611 The Suspects
    poj3436 Computer Factory
    (转) GPG入门教程
    cronolog安装配置
    RHCA-436-4 rhcs conga
    pxe引导gparted live万能分区
    linux下拔号pptp
    GNU parted简略用法
    hostapd故障解决(1.1,2.0,2.2)
  • 原文地址:https://www.cnblogs.com/sandy-t/p/13283407.html
Copyright © 2011-2022 走看看