Problem:
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”].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
思路:
本题其实就是列举若干个集合间组合的所有情况。可以用迭代的方法完成。迭代的方法如下:令当前数字与之前的所有情况result list进行组合,然后再把组合得到的结果赋值给result list,实现迭代。
Solution:
class Solution(object):
digitlist = []
count = 97
i = 0
for i in xrange(10):
tmpl = []
if i == 0 or i == 1:
digitlist.append(tmpl)
continue
elif i ==7 or i == 9:
num = 4
else:
num = 3
j = 0
for j in xrange(num):
tmpl.append(chr(count))
count += 1
digitlist.append(tmpl)
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits) == 0 :
return []
result = [""]
for s in digits:
num = int(s)
if num >=2 and num <= 9:
tmplist = []
else:
continue
for d in self.digitlist[num]:
for item in result:
tmplist.append(item+d)
result = tmplist
return result
本文介绍了一种算法,用于根据电话按键上的数字到字母映射,生成所有可能的字母组合。通过迭代方法,针对输入的数字字符串,返回其对应的所有可能的字母组合。
1097

被折叠的 条评论
为什么被折叠?



