博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode-17-电话号码的字母组合’
阅读量:4677 次
发布时间:2019-06-09

本文共 1620 字,大约阅读时间需要 5 分钟。

题目描述:

方法一:回溯

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']} def backtrack(combination, next_digits): # if there is no more digits to check if len(next_digits) == 0: # the combination is done output.append(combination) # if there are still digits to check else: # iterate over all letters which map # the next available digit 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

二:

class Solution:     def letterCombinations(self, digits):         """        :type digits: str        :rtype: List[str]        """         m = {
'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']} if not digits: return [] ls1 = [''] for i in digits: ls1 = [x + y for x in ls1 for y in m[i]] return ls1

 

转载于:https://www.cnblogs.com/oldby/p/11158338.html

你可能感兴趣的文章
poj 2828 块状链表 OR 线段树 OR 树状数组
查看>>
ios协议
查看>>
算法小记
查看>>
poj3616 LIS变形
查看>>
常用python编码
查看>>
学习笔记:树分治
查看>>
python学习笔记(七) 类和pygame实现打飞机游戏
查看>>
Guice 4.1教程
查看>>
简历已经过时了,而这里正是你需要的
查看>>
CentOS7.5删除旧的内核
查看>>
剑指Offer_57_二叉树的下一个结点
查看>>
51Nod1514 美妙的序列
查看>>
51Nod1257 背包问题 V3
查看>>
python字符串操作
查看>>
解決BufferedReader读取UTF-8文件中文乱码(转)
查看>>
OpenFire源码学习之二十六:Spark&Tinder
查看>>
window.btoa
查看>>
Linux中的会话与作业
查看>>
IE8对JS数组,采用属性遍历的解析差异
查看>>
Linux中安装JDK1.8
查看>>