標籤:

[leetcode algorithms]題目17

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"].

自己寫的代碼:

利用python的itertools完成笛卡爾積的運算,注意如果輸入為空要返回[]而不是[]。運行時間58 ms

from itertools import productclass Solution: def __init__(self): self.dic = {2: abc, 3: def, 4: ghi, 5: jkl, 6: mno, 7: pqrs, 8: tuv, 9: wxyz} def letterCombinations(self, digits): if digits: combinations = product(*[self.dic[s] for s in digits]) return [.join(x) for x in combinations] else: return []

推薦閱讀:

Leetcode-38-Count-and-Say(學渣的痛大神們不懂。。。)
【LeetCode】005-最長迴文子串
LeetCode 簡略題解 - 201~300

TAG:LeetCode |