zoukankan      html  css  js  c++  java
  • 力扣17. *的字母组合

    原题

    解法1、2都是大佬写的,题解链接

    1、回溯

     1 class Solution:
     2     def letterCombinations(self, digits: str) -> List[str]:
     3         if not digits: return []
     4 
     5         phone = {'2':['a','b','c'],
     6                  '3':['d','e','f'],
     7                  '4':['g','h','i'],
     8                  '5':['j','k','l'],
     9                  '6':['m','n','o'],
    10                  '7':['p','q','r','s'],
    11                  '8':['t','u','v'],
    12                  '9':['w','x','y','z']}
    13                 
    14         def backtrack(conbination,nextdigit):
    15             if len(nextdigit) == 0:
    16                 res.append(conbination)
    17             else:
    18                 for letter in phone[nextdigit[0]]:
    19                     backtrack(conbination + letter,nextdigit[1:])
    20 
    21         res = []
    22         backtrack('',digits)
    23         return res

    2、队列

     1 class Solution:
     2     def letterCombinations(self, digits: str) -> List[str]:
     3         if not digits: return []
     4         phone = ['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
     5         queue = ['']  # 初始化队列
     6         for digit in digits:
     7             for _ in range(len(queue)):
     8                 tmp = queue.pop(0)
     9                 for letter in phone[ord(digit)-50]:# 这里我们不使用 int() 转换字符串,使用ASCII码
    10                     queue.append(tmp + letter)
    11         return queue

    3、与大佬的相比我的代码就比较烂了

     1 class Solution:
     2     def letterCombinations(self, digits: str) -> List[str]:
     3         ans,dic,lens,cnt = [],{},len(digits),0
     4         dic['2'],dic['3'],dic['4'],dic['5'] = 'abc','def','ghi','jkl'
     5         dic['6'],dic['7'],dic['8'],dic['9'] = 'mno','pqrs','tuv','wxyz'
     6         for i in range(lens):
     7             if i == 0:
     8                 ans += ['']
     9             for j in range(len(ans)):
    10                 for c in dic[digits[i]]:
    11                     ans.append(ans[j] + c)
    12         i = len(ans) - 1
    13         while i >= 0 and len(ans[i]) == lens:
    14             i -= 1
    15         return ans[i + 1:]
    16 
    17         
  • 相关阅读:
    跑Linux内存占用率的shell脚本
    Mysql数据导入导出功能(设置及使用)
    Python刷CSDN阅读数(仅供娱乐)
    SSH、SCP命令及使用说明
    2020.6.7 时间记录
    3年经验,中级Java开发招聘信息
    中级Java程序员要求
    提升自身内部核心竞争力要素
    三级联动页面
    大公司和小公司程序员
  • 原文地址:https://www.cnblogs.com/deepspace/p/14397969.html
Copyright © 2011-2022 走看看