今天做到一个题目:
17. Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
这道题第一反应是用字典存电话按键,第二反应是多次循环迭代返回需要的list
再查了一些资料后,发现了一个迭代器的模块,找到了product函数
相关资料:http://outofmemory.cn/code-snippet/2390/python-itertools-module-learn-note
http://blog.csdn.net/neweastsun/article/details/51965226
可以直接带入array或者字符串(?)然后元素两两组合,再这道题中,先两两组合再与剩下的两两组合
上代码:
from itertools import product class Solution(object): def letterCombinations(self,digits): alpha=[] if digits=="": return [] result=[] nums={'1':'', '2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz', '0':''} alpha=[c for c in nums[digits[0]]] for i in digits[1:]: alpha=product(alpha,nums[i]) alpha=[''.join(item) for item in alpha] result=alpha return result