LeetCode-17 - Letter Combination
2017-11-21 本文已影响14人
空即是色即是色即是空
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.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Solution1
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
amap = {"2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
if not digits:
return []
return [item for item in reduce(self.combinate, [amap[i] for i in digits])]
def combinate(self, *args):
return reduce(self.join, args)
def join(self, astr, bstr):
for i in astr:
for j in bstr:
yield i+j
Solution2
更加简洁
class Solution:
# @return a list of strings, [s1, s2]
def letterCombinations(self, digits):
if '' == digits: return []
kvmaps = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
思考:
- 列表生成可以容纳多个循环体
- reduce的功能极其强大,使用之前要递归地考虑清楚
- 列表操作1
a = ['']
b = ['123']
print [i + j for i in a for j in b] # ['123']
print len(a) # 1